Welcome to our TensorFlow Image Classification Tutorial! In this hands-on guide, you'll learn how to build and train a convolutional neural network (CNN) for image classification using the CIFAR-10 dataset. This tutorial will walk you through the process of creating a deep learning model that can recognize and categorize images into predefined classes.
We'll start by loading the CIFAR-10 dataset and preprocessing the images:
import tensorflow as tf
from tensorflow.keras.datasets import cifar10
(train_images, train_labels), (test_images, test_labels) = cifar10.load_data()
# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0
Next, we'll create our CNN model using Keras:
from tensorflow.keras import layers, models
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10)
])
Now, let's compile our model with an optimizer, loss function, and metrics:
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
It's time to train our model on the training data:
history = model.fit(train_images, train_labels, epochs=10,
validation_data=(test_images, test_labels))
Finally, let's evaluate our model's performance on the test set:
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(f"\nTest accuracy: {test_acc}")
To deepen your understanding, try these exercises: