Classifying Images¶

Using the MNIST dataset built in to the tensorflow library

In [1]:
import tensorflow as tf
from tensorflow.keras.datasets import mnist
import numpy as np
import matplotlib.pyplot as plt

import warnings

warnings.filterwarnings('ignore')

Set Up Test and Training Data¶

In [2]:
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
In [3]:
training_images, test_images = training_images / 255.0, test_images / 255.0
In [4]:
for i in range(10):
    plt.subplot(2, 5, i + 1)
    plt.imshow(training_images[i], cmap='gray')
    plt.title(f"Label: {training_labels[i]}")
    plt.axis('off')
plt.show()

Design, Compile and Fit Model¶

In [5]:
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10, activation='softmax')
])
In [6]:
model.compile(optimizer='adam',

              loss='sparse_categorical_crossentropy',

              metrics=['accuracy'])
In [7]:
model.fit(training_images, training_labels, epochs=5, validation_data=(test_images, test_labels))
Epoch 1/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 2s 798us/step - accuracy: 0.8584 - loss: 0.4745 - val_accuracy: 0.9593 - val_loss: 0.1410
Epoch 2/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 1s 784us/step - accuracy: 0.9552 - loss: 0.1531 - val_accuracy: 0.9686 - val_loss: 0.1022
Epoch 3/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 1s 780us/step - accuracy: 0.9681 - loss: 0.1046 - val_accuracy: 0.9730 - val_loss: 0.0861
Epoch 4/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 1s 785us/step - accuracy: 0.9732 - loss: 0.0873 - val_accuracy: 0.9768 - val_loss: 0.0770
Epoch 5/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 1s 787us/step - accuracy: 0.9770 - loss: 0.0732 - val_accuracy: 0.9760 - val_loss: 0.0764
Out[7]:
<keras.src.callbacks.history.History at 0x15a643f10>

Import Image to Classify Prediction¶

In [8]:
image_path = 'digit.jpg'
In [9]:
from PIL import Image

image = Image.open(image_path)
image = image.resize((28, 28))
image = image.convert('L')
In [10]:
image
Out[10]:
In [11]:
image = np.array(image) / 255.0
image = np.expand_dims(image, axis=0)
In [12]:
prediction = model.predict(image)

predicted_class = np.argmax(prediction, axis=1)[0]
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 15ms/step
In [13]:
print("Predicted digit:", predicted_class)
Predicted digit: 8