Experiment: Digit Recognition using CNN
Aim
To design and implement a Convolutional Neural Network (CNN) model for handwritten
digit recognition using the MNIST dataset.
Theory
A Convolutional Neural Network (CNN) is a deep learning model particularly effective for
image processing tasks. It automatically extracts features such as edges, textures, and shapes
using convolutional layers.
Key Components:
1. Convolution Layer – Extracts features using filters/kernels
2. Activation Function (ReLU) – Introduces non-linearity
3. Pooling Layer (MaxPooling) – Reduces spatial dimensions
4. Flatten Layer – Converts 2D feature maps to 1D vector
5. Fully Connected Layer (Dense) – Performs classification
6. Output Layer (Softmax) – Produces probability for 10 digits (0–9)
Dataset
● MNIST Dataset
● 70,000 grayscale images (28×28 pixels)
● 10 classes (digits 0–9)
Algorithm
1. Load the MNIST dataset
2. Normalize pixel values (0–255 → 0–1)
3. Reshape data to (28, 28, 1)
4. Build CNN model:
o Convolution + ReLU
o MaxPooling
o Flatten
o Dense layers
5. Compile model using:
o Optimizer: Adam
o Loss: Categorical Crossentropy
6. Train the model
7. Evaluate accuracy
8. Predict digits
Program (Python using TensorFlow/Keras)
# Import required libraries
import tensorflow as tf
from [Link] import layers, models
from [Link] import mnist
from [Link] import to_categorical
import [Link] as plt
# 1. Load Dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 2. Preprocessing
# Normalize pixel values (0-255 to 0-1)
x_train = x_train / 255.0
x_test = x_test / 255.0
# Reshape dataset to include channel dimension
x_train = x_train.reshape(-1, 28, 28, 1)
x_test = x_test.reshape(-1, 28, 28, 1)
# Convert labels to one-hot encoding
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
# 3. Build CNN Model
model = [Link]()
# First Convolution Layer
[Link](layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)))
[Link](layers.MaxPooling2D((2,2)))
# Second Convolution Layer
[Link](layers.Conv2D(64, (3,3), activation='relu'))
[Link](layers.MaxPooling2D((2,2)))
# Flatten Layer
[Link]([Link]())
# Fully Connected Layer
[Link]([Link](128, activation='relu'))
# Output Layer
[Link]([Link](10, activation='softmax'))
# 4. Compile Model
[Link](
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
# 5. Train Model
history = [Link](
x_train, y_train,
epochs=5,
batch_size=64,
validation_split=0.1
)
# 6. Evaluate Model
test_loss, test_acc = [Link](x_test, y_test)
print("Test Accuracy:", test_acc)
# 7. Predict Example
import numpy as np
index = 0 # Change index to test different images
prediction = [Link](x_test[index].reshape(1,28,28,1))
print("Predicted Digit:", [Link](prediction))
print("Actual Digit:", [Link](y_test[index]))
# Display image
[Link](x_test[index].reshape(28,28), cmap='gray')
[Link]("Digit Image")
[Link]()
# 8. Plot Accuracy Graph
[Link]([Link]['accuracy'], label='Train Accuracy')
[Link]([Link]['val_accuracy'], label='Validation Accuracy')
[Link]()
[Link]("Epochs")
[Link]("Accuracy")
[Link]("Model Accuracy")
[Link]()
Output
Epoch 1/5
844/844 ━━━━━━━━━━━━━━━━━━━━ 13s 13ms/step - accuracy: 0.9480 - loss: 0.1714 -
val_accuracy: 0.9800 - val_loss: 0.0663
Epoch 2/5
844/844 ━━━━━━━━━━━━━━━━━━━━ 8s 10ms/step - accuracy: 0.9841 - loss: 0.0515 -
val_accuracy: 0.9888 - val_loss: 0.0357
Epoch 3/5
844/844 ━━━━━━━━━━━━━━━━━━━━ 9s 11ms/step - accuracy: 0.9888 - loss: 0.0353 -
val_accuracy: 0.9908 - val_loss: 0.0352
Epoch 4/5
844/844 ━━━━━━━━━━━━━━━━━━━━ 9s 10ms/step - accuracy: 0.9919 - loss: 0.0250 -
val_accuracy: 0.9895 - val_loss: 0.0420
Epoch 5/5
844/844 ━━━━━━━━━━━━━━━━━━━━ 9s 10ms/step - accuracy: 0.9941 - loss: 0.0194 -
val_accuracy: 0.9910 - val_loss: 0.0308
313/313 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.9918 - loss: 0.0269
Test Accuracy: 0.9918000102043152
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 71ms/step
Predicted Digit: 7
Actual Digit: 7
● The model achieves approximately 99.18% accuracy on test data.
Conclusion
CNNs are highly effective for image classification tasks. The model demonstrates excellent
performance in recognizing handwritten digits and can be extended to real-world applications
like postal code recognition etc.