Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathNeural Networks from Scratch to Embeddings
  1. 1
    Why Neural Networks: Pixels, One Neuron and Layers
  2. 2
    The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
  3. 3
    Loss and Backpropagation: How Wrong, and Who Is to Blame
  4. 4
    The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
  5. 5
    Your First Neural Network with Keras: MNIST Digits at 97.7%
  6. 6
    The Same Network in PyTorch: DataLoader, nn.Module and the Five-Line Training Loop
  7. 7
    Convolutional Neural Networks (CNN) Basics: Filters, Feature Maps and Pooling
  8. 8
    Embeddings: Words as Vectors, Cosine Similarity and nn.Embedding
  9. 9
    Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Deep Learning

Learning path: Neural Networks from Scratch to Embeddings · Step 5 of 9

Your First Neural Network with Keras: MNIST Digits at 97.7%

Build the 784-128-10 digit network in Keras in five steps: load and scale, Sequential with Flatten and Dense, compile, fit for ten epochs, and test once. It reads handwritten digits with 97.72% test accuracy.

Chaand Sheikh

·27 November 2026Deep Learning

What you will learn

  • Load and scale MNIST with keras.datasets
  • Build a Sequential model with Flatten and two Dense layers and check its 101,770 parameters
  • Compile with Adam and sparse_categorical_crossentropy, then fit with validation_split
  • Read the loss curves, then test once and predict one digit

Before you start

  • The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
  • Basic Python and NumPy

How does a child learn to read handwriting? With thousands of examples. Every 5, every 0, every 4, written a little differently by different hands. The child guesses ("is it a 3?"), the teacher says "no, it's a 5", and the child makes a small correction. Again and again.

Our network learns exactly the same way. The examples are the training data, the correction is the loss and backpropagation, and "again and again" is the epochs. In this article we build the digit network for real, with Keras, in five steps: load, build, compile, fit, test.

Step 1: load and scale

import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import numpy as np
import pandas as pd
import keras
import matplotlib.pyplot as plt
from keras import layers

keras.utils.set_random_seed(42)

mnist = keras.datasets.mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
print(X_train.shape, X_test.shape)
print("before:", X_train.min(), "to", X_train.max())

X_train = X_train / 255.0
X_test = X_test / 255.0
print("after: ", X_train.min(), "to", X_train.max())
(60000, 28, 28) (10000, 28, 28)
before: 0 to 255
after:  0.0 to 1.0

load_data() gives 60,000 training and 10,000 test images, each 28 x 28, with their labels. Dividing by 255 puts every pixel between 0 and 1. Small, even inputs make training much smoother.

Step 2: the Sequential model

keras.Sequential means the layers run one after another:

model = keras.Sequential([
    keras.Input(shape=(28, 28)),
    layers.Flatten(),
    layers.Dense(128, activation="relu"),
    layers.Dense(10, activation="softmax"),
])
for layer in model.layers:
    print(layer.name, layer.count_params())
print("total", model.count_params())
flatten 0
dense 100480
dense_1 1290
total 101770
The digit network, layer by layer picture 28 x 28 Flatten 784 numbers Dense 128 ReLU Dense 10 softmax 0 params 100,480 1,290 total 101,770
Flatten only reshapes. The two Dense layers hold all 101,770 weights and biases.
  • Flatten turns 28 x 28 into 784 numbers. It has no weights, it only reshapes.
  • Dense(128, relu) is the hidden layer. Each of its 128 neurons looks at every pixel: 784 x 128 + 128 = 100,480 parameters.
  • Dense(10, softmax) gives one probability per digit: 128 x 10 + 10 = 1,290 more.

101,770 in total, the same count we made by hand in The Forward Pass and Activation Functions.

Step 3: compile

model.compile(optimizer="adam",
              loss="sparse_categorical_crossentropy",
              metrics=["accuracy"])

Compile picks three things:

  • optimizer: Adam, which decides how the weights step (see The Training Loop).
  • loss: cross-entropy. Sparse means our labels are plain numbers like 7, not one-hot rows.
  • metrics: accuracy, just a score for us to read.

Compile only sets things up. Training starts when fit runs.

Step 4: fit for ten epochs

history = model.fit(X_train, y_train,
                    epochs=10, batch_size=32,
                    validation_split=0.2, verbose=0)
cols = ["loss", "val_loss", "val_accuracy"]
h = pd.DataFrame(history.history)[cols]
h.index = range(1, 11)
h.round(3)
     loss  val_loss  val_accuracy
1   0.283     0.157         0.955
2   0.125     0.117         0.965
3   0.086     0.102         0.971
4   0.063     0.097         0.972
5   0.048     0.096         0.973
6   0.036     0.097         0.973
7   0.027     0.100         0.973
8   0.020     0.094         0.976
9   0.016     0.102         0.975
10  0.015     0.097         0.977

fit is the whole training loop in one line. validation_split=0.2 holds back the last 20% of the training images (12,000) for validation; the network never trains on them. The other 48,000 go in batches of 32, which is 1,500 steps per epoch.

The training loss falls from 0.283 to 0.015. The validation accuracy goes from 95.5% after epoch 1 to 97.7% after epoch 10, on 12,000 images the network never trained on.

Training loss against validation loss

Accuracy isn't the whole story. Draw the two loss curves:

plt.plot(h.index, h["loss"], label="training")
plt.plot(h.index, h["val_loss"], label="validation")
plt.xlabel("epoch")
plt.ylabel("loss")
plt.legend()
plt.show()
Line chart over 10 epochs. The blue training loss falls steeply from about 0.28 to about 0.015. The orange validation loss drops from about 0.16 to about 0.10 by epoch 3 and then stays flat near 0.1.
The training loss keeps falling; the validation loss flattens out near 0.1.
best = h["val_loss"].idxmin()
print("lowest validation loss at epoch", best)
lowest validation loss at epoch 8

After epoch 8 the gap between the two lines only widens. That's the start of overfitting, so for this network around five to eight epochs is enough.

Step 5: test once, at the very end

loss, acc = model.evaluate(X_test, y_test, verbose=0)
print("test accuracy:", round(acc, 4))

probs = model.predict(X_test[:1], verbose=0)[0]
digit = probs.argmax()
print("true", y_test[0], "predicted", digit)
print("probability:", round(float(probs[digit]), 2))
test accuracy: 0.9772
true 7 predicted 7
probability: 1.0

evaluate scores the network on the 10,000 test images: 97.72% right on digits it has never seen. predict returns ten probabilities for the first test digit, and argmax picks the biggest. The true label is 7, the network says 7, with a probability of 1.0 after rounding.

Common mistakes

  • Forgetting to scale the pixels. Feed 0 to 255 straight in and training is much rougher.
  • Using categorical_crossentropy with plain-number labels. Labels like 7 need the sparse version.
  • Thinking compile trains the model. Nothing is learned until fit.
  • Testing after every change. Use the validation numbers while you tune; evaluate on the test set once.

Quick recap

StepCodeResult
Load and scalemnist.load_data(), / 255.0Pixels 0.0 to 1.0
BuildSequential, Flatten, Dense101,770 parameters
Compile"adam", "sparse_categorical_crossentropy"Ready to train
Fitepochs=10, validation_split=0.2val accuracy 0.977, best val loss at epoch 8
Test oncemodel.evaluate0.9772

Keras is the quick first build. Next, the same network with the loop written out by hand: The Same Network in PyTorch.

Try it yourself

Change Dense(128, ...) to Dense(32, ...) and fit again. What happens to the parameter count and to the validation accuracy?

The notebook and mnist.npz are in the StudyEasy AI Community, free to join.

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
← Previous
The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
Next →
The Same Network in PyTorch: DataLoader, nn.Module and the Five-Line Training Loop
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
Why Neural Networks: Pixels, One Neuron and Layers

Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.

The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax

Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.

Loss and Backpropagation: How Wrong, and Who Is to Blame

The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.

The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers

How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.

On this page
  • Step 1: load and scale
  • Step 2: the Sequential model
  • Step 3: compile
  • Step 4: fit for ten epochs
  • Training loss against validation loss
  • Step 5: test once, at the very end
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.