Using the MNIST dataset built in to the tensorflow library
import tensorflow as tf
from tensorflow.keras.datasets import mnist
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_images, test_images = training_images / 255.0, test_images / 255.0
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()
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')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
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
<keras.src.callbacks.history.History at 0x15a643f10>
image_path = 'digit.jpg'
from PIL import Image
image = Image.open(image_path)
image = image.resize((28, 28))
image = image.convert('L')
image
image = np.array(image) / 255.0
image = np.expand_dims(image, axis=0)
prediction = model.predict(image)
predicted_class = np.argmax(prediction, axis=1)[0]
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 15ms/step
print("Predicted digit:", predicted_class)
Predicted digit: 8