Here's a well-documented example of how to train a Convolutional Neural Network (CNN) using Keras (via TensorFlow) for image classification on the CIFAR-10 dataset.
🧠 Overview
This code trains a CNN model to classify images into one of 10 categories (e.g., airplane, car, bird, etc.) using the CIFAR-10 dataset. The architecture includes convolutional layers, pooling, flattening, and dense layers for classification.
📦 Required Libraries
import tensorflow as tf
from tensorflow.keras import layers, models, datasets
import numpy as np
📥 Load and Preprocess the Data
# Load CIFAR-10 dataset
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
# Normalize pixel values to [0, 1]
train_images, test_images = train_images / 255.0, test_images / 255.0
# Convert labels to one-hot encoded vectors
train_labels = tf.keras.utils.to_categorical(train_labels, 10)
test_labels = tf.keras.utils.to_categorical(test_labels, 10)
🏗️ Build the CNN Model
model = models.Sequential([
# Input layer and first Conv2D block
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
layers.MaxPooling2D((2, 2)),
# Second Conv2D block
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
# Third Conv2D block
layers.Conv2D(128, (3, 3), activation='relu'),
# Flatten and feed into dense layers
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dropout(0.5), # Regularization
# Output layer
layers.Dense(10, activation='softmax') # 10 classes
])
⚙️ Compile the Model
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
🚀 Train the Model
history = model.fit(train_images, train_labels,
epochs=10,
batch_size=64,
validation_split=0.2)
🧪 Evaluate the Model
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(f"Test accuracy: {test_acc:.4f}")
📝 Notes
- Input Shape: Images in CIFAR-10 are 32x32 pixels with 3 color channels (RGB), so
input_shape=(32, 32, 3).
- Epochs: You can increase
epochs for better performance (e.g., 25–50).
- Batch Size: Adjust based on your system's memory.
- Dropout: Helps prevent overfitting.
- Custom Datasets: For custom image datasets, use
ImageDataGenerator with flow_from_directory().
✅ Example Output
Epoch 1/10
625/625 [==============================] - 15s 15ms/step - loss: 1.5023 - accuracy: 0.4521
...
Epoch 10/10
625/625 [==============================] - 9s 15ms/step - loss: 0.6521 - accuracy: 0.7753
Test accuracy: 0.7345
This example provides a solid foundation for building and training CNNs using Keras. You can enhance it further by adding data augmentation, transfer learning, or more complex architectures like ResNet or VGG.