Freedom Sale
Independence Day Special — Unlock the AI Path 70% off our most popular AI course · Limited time offer
--Days
--Hrs
--Min
--Sec
Claim Your Discount
✦ Intermediate ⏱ 60 min

🖼️ Build an Image Classifier with TensorFlow and Keras

🎯 What You'll Build

A convolutional neural network that classifies handwritten digits from the MNIST dataset with 99%+ accuracy.

📋 What You'll Need

1

Load and prepare MNIST

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)
2

Build the CNN

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()
3

Train and evaluate

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
💡 Tip: Add data augmentation (random rotations, shifts) with tf.keras.layers.RandomRotation — it pushes test accuracy to 99.3%+ and prevents overfitting.

🎉 You Did It!

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.

Found something wrong?

Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.