The user wants a program for image classification using Convolutional Neural Networks (CNNs).
I need to provide a complete, runnable example.
The most common and beginner-friendly library for this is TensorFlow (Keras) or PyTorch.
I will choose TensorFlow/Keras because its API is very high-level and readable for this specific task.
I need a dataset. The CIFAR-10 or Fashion-MNIST datasets are standard and built-in. CIFAR-10 is better because it uses color images (3 channels), which makes the CNN more representative of real-world scenarios than grayscale MNIST.
So, the steps will be:
- Imports: TensorFlow, layers, models, matplotlib (for plotting).
- Load Dataset: Use
cifar10.load_data().
- Preprocessing: Normalize pixel values (0-255 -> 0-1).
- Build the CNN:
- Conv2D layers (feature extraction).
- MaxPooling2D layers (downsampling).
- Flatten layer (converting 2D maps to 1D vector).
- Dense layers (classification).
- Compile: Optimizer (Adam), Loss (Sparse Categorical Crossentropy), Metrics (Accuracy).
- Train:
model.fit().
- Evaluate:
model.evaluate().
- Visualize: Show training history (accuracy/loss over epochs) and predict on a sample image.
I should add comments explaining why specific layers or hyperparameters are chosen (e.g., ReLU activation, Softmax output).
Let's structure the code clearly.
- Language: Python
- Library: TensorFlow/Keras
- Dataset: CIFAR-10 (tiny images of 10 classes like airplane, car, bird, cat, etc.)
Drafting the code mentally:
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
# Load
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
# Normalize
train_images, test_images = train_images / 255.0, test_images / 255.0
# Model
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10)) # No softmax if using from_logits=True in loss, or add softmax.
# Compile
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# Train
history = model.fit(train_images, train_labels, epochs=10,
validation_data=(test_images, test_labels))
This looks solid. I will wrap it in a complete script with visualization code to make it more "ready to run" and useful.
I should also briefly mention PyTorch just in case the user prefers that, but providing one strong example is usually better than two mediocre ones. I'll stick to TensorFlow for the main code block.
Double check requirements: "Write a program". Okay, the code is the main output. I will add explanations around it.
Refining the code structure:
- Check for GPU availability (good practice).
- Define class names for CIFAR-10 so the output is readable.
- Plotting function is helpful.
Final check of the CNN architecture:
- Input: 32x32x3
- Conv(32) -> 30x30x32 -> Pool -> 15x15x32
- Conv(64) -> 13x13x64 -> Pool -> 6x6x64
- Conv(64) -> 4x4x64
- Flatten -> Dense(64) -> Dense(10)
This is a standard, lightweight architecture for CIFAR-10. It won't get state-of-the-art accuracy but it runs fast and demonstrates the concept well.
I will provide the Python code using TensorFlow/Keras. It is the industry standard for quickly prototyping CNNs.
Here is a complete Python program using the TensorFlow/Keras library to perform image classification on the CIFAR-10 dataset.
This dataset contains 60,000 color images (32x32 pixels) divided into 10 classes (e.g., airplane, automobile, bird, cat, etc.).
Prerequisites
You will need to install TensorFlow and Matplotlib:
pip install tensorflow matplotlib
The Python Program
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
import numpy as np
def run_cnn_classification():
# ==========================================
# 1. Load and Preprocess Dataset
# ==========================================
print("Loading CIFAR-10 dataset...")
# The dataset comes pre-split into training and testing sets
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0
# Define class names for readable predictions
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck']
print(f"Training data shape: {train_images.shape}")
print(f"Test data shape: {test_images.shape}")
# ==========================================
# 2. Build the Convolutional Neural Network (CNN)
# ==========================================
print("Building model...")
model = models.Sequential()
# --- Feature Extraction (Convolutional Base) ---
# Layer 1: Conv2D with 32 filters, 3x3 kernel
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2))) # Downsample
# Layer 2: Conv2D with 64 filters
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
# Layer 3: Conv2D with 64 filters
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
# --- Classification (Dense Layers) ---
model.add(layers.Flatten()) # Flatten 3D outputs to 1D
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10)) # Output layer: 10 classes
# Display model architecture
model.summary()
# ==========================================
# 3. Compile the Model
# ==========================================
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# ==========================================
# 4. Train the Model
# ==========================================
print("Starting training...")
epochs = 10
history = model.fit(train_images, train_labels, epochs=epochs,
validation_data=(test_images, test_labels))
# ==========================================
# 5. Evaluate the Model
# ==========================================
print("\nEvaluating model...")
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(f'\nTest accuracy: {test_acc:.2%}')
# ==========================================
# 6. Visualization (Accuracy Graph & Prediction)
# ==========================================
# Plot Accuracy vs Epoch
plt.figure(figsize=(10, 5))
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.5, 1])
plt.legend(loc='lower right')
plt.title('Training vs Validation Accuracy')
plt.show()
# Predict on a single image
prediction_visualization(model, test_images, test_labels, class_names)
def prediction_visualization(model, images, labels, class_names):
# Grab the first 5 images from test set
images = images[:5]
labels = labels[:5]
# Add batch dimension and predict
predictions = model.predict(images)
plt.figure(figsize=(10, 5))
for i in range(5):
plt.subplot(1, 5, i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(images[i], cmap=plt.cm.binary)
# Get the index of the highest probability
predicted_label = np.argmax(predictions[i])
true_label = labels[i][0]
color = 'green' if predicted_label == true_label else 'red'
plt.xlabel(f"Pred: {class_names[predicted_label]}\nTrue: {class_names[true_label]}", color=color)
plt.suptitle("Model Predictions (Green=Correct, Red=Incorrect)")
plt.show()
if __name__ == "__main__":
run_cnn_classification()
Code Explanation
- Data Loading: We use
datasets.cifar10.load_data(). This downloads 60,000 images. We normalize the pixel values (0-255) to a range of (0-1) because neural networks converge faster with smaller input values.
- CNN Architecture:
- Conv2D: Convolutional layers detect features like edges, textures, and shapes. We use ReLU activation to introduce non-linearity.
- MaxPooling2D: This reduces the spatial dimensions (height and width) to reduce computation and prevent overfitting.
- Flatten: Converts the 2D feature maps (from the convolutions) into a 1D vector so the Dense layers can process it.
- Dense: The final classification layers. The output layer has 10 neurons (one for each class).
- Compilation: We use the Adam optimizer (standard for CNNs) and Sparse Categorical Crossentropy loss (used when classes are integers rather than one-hot vectors).
- Training: The
.fit() function iterates over the data 10 times (epochs=10), adjusting the weights to minimize loss.
- Visualization: We plot the training accuracy vs validation accuracy to check for overfitting, and we display a few test images with their predicted labels.