I'm focused on the fundamental building blocks now. It's clear I'll need a dataset, and I'm leaning toward MNIST for its simplicity. Beyond that, I need to define the CNN architecture, considering layers like convolutional, pooling, and fully connected. Then I'll work out the specifics for training and evaluating the model.
Outlining the Architecture
I've sketched out the CNN's structure. Thinking through the specifics of the convolutional and pooling layers is next, including filter sizes and stride values. The flattening and dense layers are straightforward after the convolutions are in place. Then, I will address the training and evaluation phases.
Structuring the Code Framework
I'm translating the architectural outline into code. I've initiated the import statements and data loading using TensorFlow/Keras. Currently, I'm working through data preprocessing, specifically reshaping and normalizing the MNIST dataset's pixel values. I am also considering how to best approach the labels.
Refining Data Handling
I'm now diving into the nuances of data preprocessing. I've confirmed that I'll normalize the image pixel values to the 0-1 range. I will utilize sparse_categorical_crossentropy to streamline the label handling without one-hot encoding, as it's more beginner-friendly.
Mapping Out Code Generation
I'm now methodically structuring the code. I've broken down each step, from importing libraries and loading data, to defining the model architecture, and finally, compilation, training, and evaluation. My emphasis is on clarity and conciseness, making it as beginner-friendly as possible.
Detailing Code Implementation
I'm presently building the code, methodically implementing each step. I've successfully incorporated the imports, data loading, and preprocessing, including the essential reshaping and normalization. The model definition, incorporating convolutional, pooling, and dense layers, is progressing well. I am working on the compilation and the training phases now.
Here is a complete, step-by-step Python script to classify handwritten digits using a Convolutional Neural Network (CNN).
We will use TensorFlow (Keras) as it is the industry standard and very beginner-friendly, along with the MNIST dataset (the "Hello World" of computer vision).
Prerequisites
You will need to install TensorFlow, NumPy, and Matplotlib. Run this command in your terminal:
bash
pip install tensorflow numpy matplotlib
The Python Code
Save this code into a file (e.g., digits_cnn.py) or run it in a Jupyter Notebook.
python
Explanation of Key Parts
Data Reshaping (reshape): Normal images are treated as matrices (Height x Width). However, a Convolutional Layer expects a 4D tensor: (Batch_Size, Height, Width, Color_Channels). Since MNIST is black and white, we set Color_Channels to 1.
Conv2D Layer: This is the "eye" of the AI. It slides small filters (kernels) over the image to detect features like horizontal lines, loops, or corners.
MaxPooling2D: This shrinks the image data. If the AI learned what a "loop" looks like in a 4x4 area, pooling summarizes that to a 2x2 area to reduce computation cost and prevent overfitting.
Dense Layers: These are standard neural network layers. After the Convolutional layers extract the "features," the Dense layers use those features to decide which digit it is (classification).
Softmax: This activation function turns the output into probabilities. It ensures that the sum of all 10 output neurons equals 1 (100%).
Expected Output
After running the script:
It will download the dataset (first time only).
It will display the model architecture.
You will see a training progress bar for 5 epochs (usually reaching ~99% accuracy).
Two graphs will pop up showing the training progress.
Finally, it will pick a random image from the test set, show it to you, and print the network's prediction.
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import layers, models
def main():
# ==========================================
# 1. Load and Preprocess Data
# ==========================================
print("Loading the MNIST dataset...")
mnist = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# Normalize pixel values to be between 0 and 1
# (0 is white, 1 is black in this processed dataset)
train_images, test_images = train_images / 255.0, test_images / 255.0
# Reshape the images to (Batch Size, Height, Width, Channels)
# MNIST is grayscale, so Channels = 1
train_images = train_images.reshape((-1, 28, 28, 1))
test_images = test_images.reshape((-1, 28, 28, 1))
print(f"Training data shape: {train_images.shape}")
print(f"Test data shape: {test_images.shape}")
# ==========================================
# 2. Build the CNN Architecture
# ==========================================
print("\nBuilding the model...")
model = models.Sequential()
# Convolutional Layer 1: Extracts features (edges, curves)
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
# Pooling Layer 1: Reduces dimensionality
model.add(layers.MaxPooling2D((2, 2)))
# Convolutional Layer 2
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
# Pooling Layer 2
model.add(layers.MaxPooling2D((2, 2)))
# Convolutional Layer 3
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
# Flatten Layer: Converts 2D matrix data to a 1D vector
model.add(layers.Flatten())
# Dense (Fully Connected) Layer
model.add(layers.Dense(64, activation='relu'))
# Output Layer: 10 neurons for 10 digits (0-9), Softmax returns probabilities
model.add(layers.Dense(10, activation='softmax'))
model.summary()
# ==========================================
# 3. Compile and Train the Model
# ==========================================
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
print("\nTraining the model (This may take a minute)...")
history = model.fit(train_images, train_labels,
epochs=5,
batch_size=64,
validation_split=0.1)
# ==========================================
# 4. Evaluate the Model
# ==========================================
print("\nEvaluating on test data...")
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(f"\nTest accuracy: {test_acc*100:.2f}%")
# ==========================================
# 5. Visualize Predictions
# ==========================================
plot_results(history)
visualize_prediction(model, test_images, test_labels)
def plot_results(history):
"""Helper function to plot accuracy vs epoch"""
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc) + 1)
plt.figure(figsize=(12, 5))
# Plot Accuracy
plt.subplot(1, 2, 1)
plt.plot(epochs, acc, 'bo-', label='Training acc')
plt.plot(epochs, val_acc, 'ro-', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()
# Plot Loss
plt.subplot(1, 2, 2)
plt.plot(epochs, loss, 'bo-', label='Training loss')
plt.plot(epochs, val_loss, 'ro-', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
def visualize_prediction(model, test_images, test_labels):
"""Pick a random image from test set and predict it"""
num_images = test_images.shape[0]
random_idx = np.random.randint(0, num_images)
img_to_predict = test_images[random_idx]
true_label = test_labels[random_idx]
# Add batch dimension for prediction: (1, 28, 28, 1)
img_batch = np.expand_dims(img_to_predict, axis=0)
predictions = model.predict(img_batch)
predicted_label = np.argmax(predictions)
print("------------------------------------------------")
print(f"Example Prediction for index {random_idx}:")
print(f"True Label: {true_label}")
print(f"Predicted Label: {predicted_label}")
print("------------------------------------------------")
plt.imshow(img_to_predict.reshape(28, 28), cmap=plt.cm.binary)
plt.title(f"True: {true_label}, Pred: {predicted_label}")
plt.axis('off')
plt.show()
if __name__ == "__main__":
main()