Guided project · Foundations · Algorithms in detail

Teach a neural network to read handwriting

See a neural network learn visually, then build one that recognises handwritten digits with about 97% accuracy.

About 60 minAdvancedCopy-paste code
0 of 10 steps done

What you'll build

A working neural network that reads handwritten numbers 0–9, plus a look at the mistakes it makes.

What you'll learn

  • Neurons, layers, weights and training in practice
  • Epochs, accuracy and validation
  • Why networks make mistakes, and how to see them

You'll need

TensorFlow Playground (no code) and Google Colab (free, in your browser)

Create a free account to unlock this project

The step-by-step instructions, copy-ready prompts, progress tracker and portfolio texts are for members. It's free, takes under a minute, and unlocks all guided projects.

Want to try first? These projects are open to everyone: Prompt lab and One idea, five posts.

Before you start

Use any free AI chatbot (ChatGPT, Claude, Gemini or Copilot). Never paste private or confidential information.

Step by step

  1. Warm up: watch a network learn

    Open TensorFlow Playground and press ▶. Then pick the spiral dataset (bottom-right of the DATA panel) and press ▶ again.

    You should see: The simple dataset is learned in seconds; the spiral struggles. Add hidden layers and neurons with the + buttons and the spiral gets solved.

    Why it matters: More layers let a network learn more complex shapes. That's deep learning.

  2. Open Colab and load the digits

    Create a new notebook at colab.research.google.com and run this. It downloads 70,000 small images of handwritten digits.

    Copy this code
    import tensorflow as tf
    import matplotlib.pyplot as plt
    
    (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
    print(x_train.shape, x_test.shape)

    You should see: Two shapes: (60000, 28, 28) for training and (10000, 28, 28) for testing. Each image is 28 × 28 pixels.

  3. Look at some examples

    Show the first 10 images with their correct labels.

    Copy this code
    plt.figure(figsize=(10, 2))
    for i in range(10):
        plt.subplot(1, 10, i + 1)
        plt.imshow(x_train[i], cmap='gray')
        plt.title(y_train[i]); plt.axis('off')
    plt.show()

    You should see: Ten handwritten digits with numbers above them.

  4. Prepare the pixels

    Pixel values go from 0 to 255. Networks learn better with small numbers, so scale them to 0–1.

    Copy this code
    x_train = x_train / 255.0
    x_test = x_test / 255.0

    You should see: No output. The data is now ready.

  5. Build the network

    Create 3 layers: flatten the image into 784 numbers, a hidden layer of 128 neurons, and an output layer with one neuron per digit.

    Copy this code
    model = tf.keras.Sequential([
        tf.keras.layers.Input(shape=(28, 28)),
        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()

    You should see: A summary table showing about 100,000 weights (parameters) to learn.

    Why it matters: Dropout randomly switches off some neurons during training so the network doesn't just memorise.

  6. Train it

    Show the network the training images 5 times (5 epochs). 10% are kept aside to check progress.

    Copy this code
    history = model.fit(x_train, y_train, epochs=5, validation_split=0.1)

    You should see: Accuracy climbing each epoch, to about 97–98%. It takes about a minute.

  7. Test it on unseen digits

    Measure accuracy on the 10,000 test images it has never seen.

    Copy this code
    loss, acc = model.evaluate(x_test, y_test)
    print('Test accuracy:', round(acc * 100, 1), '%')

    You should see: Test accuracy of about 97–98%.

  8. Plot the learning curve

    See how training and validation accuracy changed over the epochs.

    Copy this code
    plt.plot(history.history['accuracy'], label='training')
    plt.plot(history.history['val_accuracy'], label='validation')
    plt.xlabel('epoch'); plt.ylabel('accuracy'); plt.legend(); plt.show()

    You should see: Two rising lines. If the validation line drops while training keeps rising, that's overfitting.

  9. Look at its mistakes

    Show some test digits it got wrong, with what it guessed.

    Copy this code
    import numpy as np
    
    pred = model.predict(x_test).argmax(axis=1)
    wrong = np.where(pred != y_test)[0][:10]
    plt.figure(figsize=(10, 2))
    for n, i in enumerate(wrong):
        plt.subplot(1, 10, n + 1)
        plt.imshow(x_test[i], cmap='gray')
        plt.title(f'{pred[i]} not {y_test[i]}', fontsize=8); plt.axis('off')
    plt.show()

    You should see: Messy, unusual handwriting: often digits a person might misread too.

  10. Experiment

    Change one thing and retrain: 256 neurons instead of 128, 10 epochs instead of 5, or remove the Dropout line. Note the test accuracy each time.

    You should see: Small changes in accuracy. You're now tuning a neural network, which is what ML engineers do daily.

Level up

  • Add a second hidden layer and compare.
  • Ask an AI chatbot to convert the model into a small CNN (convolutional network) and see if accuracy rises above 99%.
  • Try the Fashion-MNIST dataset (clothes images) by changing mnist to fashion_mnist.

Lessons behind this project

Show it off

Finished? Post about it on LinkedIn. Here's a starting point; add a screenshot and your own words.

Copy this post
Today I trained a neural network that reads handwritten digits with about 98% accuracy, and looked at the mistakes it makes. Neural networks finally make sense to me! Learned with AI From Zero.
Share on LinkedIn

Add it to your portfolio

Employers love seeing what you've built. Use these ready-made texts, then add your own results and a screenshot.

1. A line for your CV or LinkedIn "Projects" section

Copy for your CV
Teach a neural network to read handwriting: A working neural network that reads handwritten numbers 0–9, plus a look at the mistakes it makes. Skills: Neurons, layers, weights and training in practice, Epochs, accuracy and validation, Why networks make mistakes, and how to see them. Tools: TensorFlow Playground (no code) and Google Colab (free, in your browser).

2. A README for GitHub

Create a free GitHub account, make a new repository, add a file called README.md and paste this in along with your notebook (File → Download → .ipynb).

Copy README.md
# Teach a neural network to read handwriting

See a neural network learn visually, then build one that recognises handwritten digits with about 97% accuracy.

## What I built
A working neural network that reads handwritten numbers 0–9, plus a look at the mistakes it makes.

## What I learned
- Neurons, layers, weights and training in practice
- Epochs, accuracy and validation
- Why networks make mistakes, and how to see them

## Tools
TensorFlow Playground (no code) and Google Colab (free, in your browser)

## How it works
1. Warm up: watch a network learn
2. Open Colab and load the digits
3. Look at some examples
4. Prepare the pixels
5. Build the network
6. Train it
7. Test it on unseen digits
8. Plot the learning curve
9. Look at its mistakes
10. Experiment

## Results
(Add a screenshot and 2–3 sentences about what you found. Never include API keys or personal data.)

## Next steps
- Add a second hidden layer and compare.
- Ask an AI chatbot to convert the model into a small CNN (convolutional network) and see if accuracy rises above 99%.
- Try the Fashion-MNIST dataset (clothes images) by changing mnist to fashion_mnist.

---
Built by following the free guided project at https://learnaifromzero.com/projects/handwriting-neural-network.html