TensorFlow Example - Image Classification Project
Image classification is one of the most fundamental and important tasks in computer vision. This project will use the TensorFlow framework to build a deep learning model capable of recognizing images of different categories.
What is image classification
Image classification refers to the technique of enabling computers to automatically identify the category of the main object in an image. For example:
- Identify whether a photo shows a cat or a dog
- Distinguish different kinds of flowers
- Determine the type of lesion in medical images
Tech stack choices
We will use the following technology stack:
- TensorFlow: The mainstream deep learning framework developed by Google
- Keras: TensorFlow's high-level API that simplifies model building
- Matplotlib: For visualizing the training process and results
Environment Preparation
Install necessary libraries
pip install tensorflow matplotlib numpy
Verify the installation
import tensorflow as tf
print(f"TensorFlow 版本: {tf.__version__}")
Dataset preparation
We will use the classic CIFAR-10 dataset, which contains 60,000 32x32 color images across 10 categories.
Load the dataset
Example
from
tensorflow.
keras
.
datasets
import
cifar10
Load data
(
train_images
,
train_labels
)
,
(
test_images
,
test_labels
)
=
cifar10.
load_data
(
)
Class name
class_names
=
[
'Airplane'
,
'Automobile'
,
'Bird'
,
'Cat'
,
'Deer'
,
'Dog'
,
'Frog'
,
'Horse'
,
'Ship'
,
'Truck'
]
3.2 Data preprocessing
Example
Normalize pixel values to the 0-1 range
train_images
=
train_images /
255.0
test_images
=
test_images /
255.0
Check data shape
(
"Training set image shape:"
,
train_images.
shape
)
(
"Training set label shape:"
,
train_labels.
shape
)
4. Build the model
4.1 Model architecture
We will build a convolutional neural network (CNN), a classic structure for handling image tasks.
Example
from
tensorflow.
keras
import
layers
,
models
model
=
models.
Sequential
(
[
Convolutional layer 1
layers.
Conv2D
(
32
,
(
3
,
3
)
,
activation
=
'relu'
,
input_shape
=
(
32
,
32
,
3
)
)
,
layers.
MaxPooling2D
(
(
2
,
2
)
)
,
Convolutional layer 2
layers.
Conv2D
(
64
,
(
3
,
3
)
,
activation
=
'relu'
)
,
layers.
MaxPooling2D
(
(
2
,
2
)
)
,
Convolutional layer 3
layers.
Conv2D
(
64
,
(
3
,
3
)
,
activation
=
'relu'
)
,
Fully connected layer
layers.
Flatten
(
)
,
layers.
Dense
(
64
,
activation
=
'relu'
)
,
layers.
Dense
(
10
)
Output layer, 10 categories
]
)
Visualize the model architecture

Train the model
Compile the model
Example
model.
compile
(
optimizer
=
'adam'
,
loss
=
tf.
keras
.
losses
.
SparseCategoricalCrossentropy
(
from_logits
=
True
)
,
metrics
=
[
'accuracy'
]
)
Start training
Example
history
=
model.
fit
(
train_images
,
train_labels
,
epochs
=
10
,
validation_data
=
(
test_images
,
test_labels
)
)
Training process visualization
Example
import
matplotlib.
pyplot
as
plt
plt.
plot
(
history.
history
[
'accuracy'
]
,
label
=
'Training accuracy'
)
plt.
plot
(
history.
history
[
'val_accuracy'
]
,
label
=
'Validation accuracy'
)
plt.
xlabel
(
'Epoch'
)
plt.
ylabel
(
'Accuracy'
)
plt.
ylim
(
[
0
,
1
]
)
plt.
legend
(
loc
=
'lower right'
)
plt.
show
(
)
Model evaluation and prediction
Evaluate test set performance
Example
test_loss
,
test_acc
=
model.
evaluate
(
test_images
,
test_labels
,
verbose
=
2
)
(
f
'\nTest accuracy: {test_acc}'
)
Make predictions
Example
import
numpy
as
np
Add a softmax layer to make outputs probabilities
probability_model
=
tf.
keras
.
Sequential
(
[
model
,
layers.
Softmax
(
)
]
)
Make predictions on the first 5 images of the test set
predictions
=
probability_model.
predict
(
test_images
[
:
5
]
)
Display prediction results
for
i
in
range
(
5
)
:
predicted_label
=
np.
argmax
(
predictions
[
i
]
)
true_label
=
test_labels
[
i
]
[
0
]
(
f
"Predicted: {class_names[predicted_label]} | Actual: {class_names[true_label]}"
)
Project extension suggestions
Methods to Improve Model Performance
- Increase network depth (more convolutional layers)
- Use data augmentation techniques
- Try different optimizers and learning rates
- Add batch normalization layers
Practical application directions
- Medical image analysis
- Object recognition in autonomous driving
- Industrial quality inspection systems
- Security monitoring systems
8. Frequently asked questions
Q1: Why choose a CNN instead of a regular neural network?
A: CNNs use local connections and weight sharing to better capture spatial features of images, with fewer parameters.
Q2: How to choose the right number of epochs?
A: Observe validation set accuracy and stop training when it no longer improves, to avoid overfitting.
Q3: What to do when encountering out-of-memory errors?
A: You can reduce the batch size or use smaller image sizes.