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

CVDL7 61

The document outlines a TensorFlow and Keras implementation of the LeNet model for classifying MNIST handwritten digits. It includes data normalization, model definition, training, evaluation, and saving the trained model, achieving a test accuracy of 98.46%. Additionally, it provides a function to predict labels for input images using the trained model.
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)
13 views3 pages

CVDL7 61

The document outlines a TensorFlow and Keras implementation of the LeNet model for classifying MNIST handwritten digits. It includes data normalization, model definition, training, evaluation, and saving the trained model, achieving a test accuracy of 98.46%. Additionally, it provides a function to predict labels for input images using the trained model.
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

3/12/25, 8:15 PM cvdl 7.

ipynb - Colab

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
import matplotlib.pyplot as plt
import cv2

(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()


x_train, x_test = x_train / 255.0, x_test / 255.0 # Normalize to [0,1]

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


11490434/11490434 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step

x_train = x_train[..., tf.newaxis]


x_test = x_test[..., tf.newaxis]

fig, axes = plt.subplots(1, 4, figsize=(12, 4))


for i, ax in enumerate(axes):
ax.imshow(x_train[i].squeeze(), cmap='gray') # Indented this line
ax.set_title(f'Label: {y_train[i]}') # Indented this line
ax.axis('off') # Indented this line
plt.show()

def LeNet():
model = keras.Sequential([
layers.Conv2D(6, kernel_size=5, activation='tanh', padding='same', input_shape=(28, 28, 1)),
layers.AvgPool2D(pool_size=2, strides=2),
layers.Conv2D(16, kernel_size=5, activation='tanh'),
layers.AvgPool2D(pool_size=2, strides=2),
layers.Flatten(),
layers.Dense(120, activation='tanh'),
layers.Dense(84, activation='tanh'),
layers.Dense(10, activation='softmax')
])
return model

# Define the model first


model = LeNet()
# Now you can compile it
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_test, y_test))

test_loss, test_acc = model.evaluate(x_test, y_test)


print(f"Test Accuracy: {test_acc:.4f}")

# Save the trained model


model.save("lenet_mnist.h5")

/usr/local/lib/python3.11/dist-packages/keras/src/layers/convolutional/base_conv.py:107: UserWarning: Do not pass an `input_shape`/`


super().__init__(activity_regularizer=activity_regularizer, **kwargs)
Epoch 1/10
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 47s 23ms/step - accuracy: 0.8753 - loss: 0.4101 - val_accuracy: 0.9642 - val_loss: 0.1116
Epoch 2/10
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 44s 23ms/step - accuracy: 0.9698 - loss: 0.0968 - val_accuracy: 0.9790 - val_loss: 0.0677
Epoch 3/10
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 80s 22ms/step - accuracy: 0.9822 - loss: 0.0586 - val_accuracy: 0.9790 - val_loss: 0.0683
Epoch 4/10
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 40s 22ms/step - accuracy: 0.9859 - loss: 0.0447 - val_accuracy: 0.9831 - val_loss: 0.0551
Epoch 5/10
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 44s 23ms/step - accuracy: 0.9902 - loss: 0.0320 - val_accuracy: 0.9811 - val_loss: 0.0609
Epoch 6/10
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 83s 24ms/step - accuracy: 0.9908 - loss: 0.0299 - val_accuracy: 0.9832 - val_loss: 0.0537
Epoch 7/10
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 81s 23ms/step - accuracy: 0.9916 - loss: 0.0251 - val_accuracy: 0.9863 - val_loss: 0.0456
Epoch 8/10

https://colab.research.google.com/drive/1z4qsPvWNq_KgUB_5q5N0OFY80VOZUeg4#scrollTo=29cSEMWxx-Vn&printMode=true 1/3
3/12/25, 8:15 PM cvdl 7.ipynb - Colab
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 81s 23ms/step - accuracy: 0.9935 - loss: 0.0207 - val_accuracy: 0.9870 - val_loss: 0.0449
Epoch 9/10
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 79s 21ms/step - accuracy: 0.9944 - loss: 0.0169 - val_accuracy: 0.9869 - val_loss: 0.0419
Epoch 10/10
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 43s 23ms/step - accuracy: 0.9952 - loss: 0.0148 - val_accuracy: 0.9846 - val_loss: 0.0544
313/313 ━━━━━━━━━━━━━━━━━━━━ 3s 9ms/step - accuracy: 0.9815 - loss: 0.0629
WARNING:absl:You are saving your model as an HDF5 file via `model.save()` or `keras.saving.save_model(model)`. This file format is c
Test Accuracy: 0.9846

def predict(image_path, model_path="lenet_mnist.h5"):


# Indent all lines within the function body
model = keras.models.load_model(model_path)
image = cv2.imread(image_path)
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (28, 28))
img = cv2.bitwise_not(img)
img = img / 255.0
img = img.reshape(1, 28, 28, 1)
prediction = model.predict(img)
predicted_label = np.argmax(prediction)
plt.imshow(image.squeeze())
plt.title(f"Predicted Label: {predicted_label}")
plt.axis("off")
plt.show()

predict("/content/download.png")

WARNING:absl:Compiled the loaded model, but the compiled metrics have yet to be built. `model.compile_metrics` will be empty until y
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 156ms/step

def predict(image_path, model_path="lenet_mnist.h5"):


# Indent all lines within the function body
model = keras.models.load_model(model_path)
image = cv2.imread(image_path)
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (28, 28))
img = cv2.bitwise_not(img)
img = img / 255.0
img = img.reshape(1, 28, 28, 1)
prediction = model.predict(img)
predicted_label = np.argmax(prediction)
plt.imshow(image.squeeze())
plt.title(f"Predicted Label: {predicted_label}")
plt.axis("off")
plt.show()

predict("/content/33.jpg")

https://colab.research.google.com/drive/1z4qsPvWNq_KgUB_5q5N0OFY80VOZUeg4#scrollTo=29cSEMWxx-Vn&printMode=true 2/3
3/12/25, 8:15 PM cvdl 7.ipynb - Colab

WARNING:absl:Compiled the loaded model, but the compiled metrics have yet to be built. `model.compile_metrics` will be empty until y
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 120ms/step

def predict(image_path, model_path="lenet_mnist.h5"):


# Indent all lines within the function body
model = keras.models.load_model(model_path)
image = cv2.imread(image_path)
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (28, 28))
img = cv2.bitwise_not(img)
img = img / 255.0
img = img.reshape(1, 28, 28, 1)
prediction = model.predict(img)
predicted_label = np.argmax(prediction)
plt.imshow(image.squeeze())
plt.title(f"Predicted Label: {predicted_label}")
plt.axis("off")
plt.show()

predict("/content/download 4.jpg")

WARNING:absl:Compiled the loaded model, but the compiled metrics have yet to be built. `model.compile_metrics` will be empty until y
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 127ms/step

Start coding or generate with AI.

https://colab.research.google.com/drive/1z4qsPvWNq_KgUB_5q5N0OFY80VOZUeg4#scrollTo=29cSEMWxx-Vn&printMode=true 3/3

You might also like