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 Data
# ==========================================
print("Loading CIFAR-10 dataset...")
# CIFAR-10 contains 60,000 32x32 color images in 10 classes.
(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 reference
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 CNN Architecture
# ==========================================
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))) # Reduces spatial dimensions
# 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 (Optional)
# ==========================================
# Plot training accuracy vs validation accuracy
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()
# ==========================================
# 7. Prediction Example
# ==========================================
# Grab the first 5 images from test set to predict
predictions = model.predict(test_images[:5])
print("\n--- Sample Predictions ---")
for i in range(5):
# Convert raw logits to probabilities using softmax
score = tf.nn.softmax(predictions[i])
predicted_label = class_names[np.argmax(score)]
actual_label = class_names[test_labels[i][0]]
print(f"Image {i+1}: Predicted: {predicted_label}, Actual: {actual_label}")
if __name__ == "__main__":
run_cnn_classification()