A convolutional neural network that classifies handwritten digits from the MNIST dataset with 99%+ accuracy.
Keras ships MNIST — normalise and reshape for the CNN.
import tensorflow as tf
import numpy as np
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# Normalise to [0, 1] and add channel dimension
x_train = x_train[..., np.newaxis] / 255.0
x_test = x_test[..., np.newaxis] / 255.0
print(f"Train: {x_train.shape}, Test: {x_test.shape}")
Train: (60000, 28, 28, 1), Test: (10000, 28, 28, 1)
Two conv layers, a pooling layer, and a dense output.
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(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.summary()
Five epochs is enough to cross 99% accuracy.
history = model.fit(x_train, y_train, epochs=5, validation_split=0.1, batch_size=128, verbose=1)
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
print(f"\nTest accuracy: {test_acc:.4f}")
# Plot training curves
import matplotlib.pyplot as plt
plt.plot(history.history['accuracy'], label='train')
plt.plot(history.history['val_accuracy'], label='val')
plt.title('Accuracy per Epoch')
plt.legend()
plt.savefig('cnn_accuracy.png', dpi=150)
Epoch 5/5 — accuracy: 0.9934 — val_accuracy: 0.9921 Test accuracy: 0.9921
You trained a CNN that recognises handwritten digits with 99.2% accuracy. Swap MNIST for your own image folders using tf.keras.utils.image_dataset_from_directory.
Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.