0% found this document useful (0 votes)
16 views3 pages

CNN Train Mnist

This document describes building and training a convolutional neural network (CNN) model for classifying MNIST handwritten digits. First, the MNIST dataset is loaded and preprocessed. A CNN model is defined with convolutional and max pooling layers, followed by dense layers. The model is compiled and trained on the train dataset for 5 epochs, with validation on the test dataset. The trained model achieves over 99% test accuracy on the held-out test images and labels.

Uploaded by

rajbarhuliya65
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views3 pages

CNN Train Mnist

This document describes building and training a convolutional neural network (CNN) model for classifying MNIST handwritten digits. First, the MNIST dataset is loaded and preprocessed. A CNN model is defined with convolutional and max pooling layers, followed by dense layers. The model is compiled and trained on the train dataset for 5 epochs, with validation on the test dataset. The trained model achieves over 99% test accuracy on the held-out test images and labels.

Uploaded by

rajbarhuliya65
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

untitled1-1

February 19, 2024

[14]: import tensorflow as tf


import matplotlib.pyplot as plt
import numpy as np

[2]: # Load and preprocess the MNIST dataset


mnist = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images, test_images = train_images / 255.0, test_images / 255.0 #␣
↪Normalize pixel values to [0, 1]

Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-


datasets/mnist.npz
11490434/11490434 [==============================] - 1s 0us/step

[3]: # Define the CNN model


model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28,␣
↪1)),

tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])

[10]: # Display the first 10 images from the training set with colorful borders and␣
↪styled titles

plt.figure(figsize=(14, 2))
for i in range(10):
ax = plt.subplot(1, 10, i+1)
plt.imshow(train_images[i], cmap='gray')

color = plt.cm.tab10(train_labels[i] / 9) # Use a different color for each␣


↪digit label
rect = plt.Rectangle((0, 0), 27, 27, linewidth=2, edgecolor=color,␣
↪fill=False)

1
ax.add_patch(rect)

ax.set_title(train_labels[i], fontsize=12, color=color, fontweight='bold',␣


↪pad=2)

plt.axis('off')

plt.subplots_adjust(wspace=0.3) # Adjust spacing between subplots


plt.show()

[5]: # Reshape the input images to (28, 28, 1) to match the input shape of the model
train_images = train_images.reshape(-1, 28, 28, 1)
test_images = test_images.reshape(-1, 28, 28, 1)

[12]: # Compile the model


model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])

[7]: # Train the model


model.fit(train_images, train_labels, epochs=5, validation_data=(test_images,␣
↪test_labels))

Epoch 1/5
1875/1875 [==============================] - 69s 36ms/step - loss: 0.1480 -
accuracy: 0.9554 - val_loss: 0.0522 - val_accuracy: 0.9832
Epoch 2/5
1875/1875 [==============================] - 56s 30ms/step - loss: 0.0445 -
accuracy: 0.9861 - val_loss: 0.0366 - val_accuracy: 0.9875
Epoch 3/5
1875/1875 [==============================] - 53s 28ms/step - loss: 0.0305 -
accuracy: 0.9903 - val_loss: 0.0309 - val_accuracy: 0.9896
Epoch 4/5
1875/1875 [==============================] - 54s 29ms/step - loss: 0.0234 -
accuracy: 0.9923 - val_loss: 0.0447 - val_accuracy: 0.9860
Epoch 5/5
1875/1875 [==============================] - 53s 28ms/step - loss: 0.0177 -
accuracy: 0.9942 - val_loss: 0.0315 - val_accuracy: 0.9906

[7]: <keras.src.callbacks.History at 0x7e9caab43c10>

2
[8]: # Evaluate the model
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f'Test accuracy: {test_acc*100}')

313/313 [==============================] - 3s 9ms/step - loss: 0.0315 -


accuracy: 0.9906
Test accuracy: 99.05999898910522

[8]:

You might also like