EXP NO 5 Handwritten Digit Classification using
DATE Neural Networks
AIM :
To implement a neural network model using TensorFlow and Keras for
classifying handwritten digits from the MNIST dataset.
PROCEDURE :
[Link] necessary libraries (tensorflow, numpy, matplotlib).
[Link] and preprocess the MNIST dataset (normalize pixel values,
apply one-hot encoding).
[Link] sample images from the training set.
[Link] a neural network with three layers (Flatten, Dense with ReLU,
and Softmax output).
[Link] and train the model using Adam optimizer and categorical
cross-entropy loss.
[Link] the model on test data and display accuracy.
[Link] and visualize results for five random test images.
PROGRAM :
import tensorflow as tf
import [Link] as plt
import numpy as np
from [Link] import mnist
from [Link] import Sequential
from [Link] import Dense, Flatten
from [Link] import to_categorical
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
y_train, y_test = to_categorical(y_train, 10), to_categorical(y_test, 10)
fig, axes = [Link](1, 5, figsize=(10, 2))
for i, ax in enumerate(axes):
[Link](x_train[i], cmap='gray')
[Link]('off')
[Link]()
model = Sequential([
Flatten(input_shape=(28, 28)),
Dense(128, activation='relu'),
Dense(64, activation='relu'),
Dense(10, activation='softmax')
])
[Link](optimizer='adam', loss='categorical_crossentropy',
metrics=['accuracy'])
history = [Link](x_train, y_train, epochs=10, validation_split=0.2,
verbose=0)
test_loss, test_acc = [Link](x_test, y_test)
print(f"Test Accuracy: {test_acc:.2f}")
sample_idx = [Link](len(x_test), 5, replace=False)
x_sample, y_sample = x_test[sample_idx], y_test[sample_idx]
predictions = [Link](x_sample)
fig, axes = [Link](1, 5, figsize=(10, 2))
for i, ax in enumerate(axes):
[Link](x_sample[i], cmap='gray')
[Link]('off')
ax.set_title(f"P: {[Link](predictions[i])}", color='green')
[Link]()
OUTPUT :
313/313 ━━━━━━━━━━━━━━━━━━━━ 1s 2ms/step -
accuracy: 0.9721 - loss: 0.1119
Test Accuracy: 0.98
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 61ms/step
RESULT :
The neural network successfully classified handwritten digits from the
MNIST dataset with high accuracy.