Learning enough machine learning to build a CNN
In July 2025 I needed an app to read children's handwriting, which meant training a neural network. Before I wrote the training script I wanted to understand what each line of it would actually do, rather than copying a tutorial and hoping.
Each idea below only needs the ones before it.
Where the training data comes from
A network learns from examples, so before anything else you need a lot of labelled handwriting. I used EMNIST, short for Extended MNIST.
MNIST is the classic starter dataset, 70,000 handwritten digits from 0 to 9. EMNIST was released in 2017 by researchers at Western Sydney University and adds letters. They took an old American collection of handwriting, NIST Special Database 19, which came from forms filled in by Census Bureau staff and high school students, and converted it into exactly the same format as MNIST. Every character is a centred 28×28 greyscale image, so anything written for MNIST works on EMNIST almost unchanged.
It comes in several splits. ByClass has all 62 classes (digits, capitals and lowercase) across about 814,000 images, though some letters have far more examples than others. Letters has 26 classes and about 145,000 images, with each letter's upper and lower case merged into one class. There are a few others, including versions that only merge letters which look the same in both cases, like C and c.
It's free, big and well understood, which made it the obvious place to start. Its weakness for my purposes was the handwriting itself. Adults filling in American forms decades ago don't write much like a six-year-old on an iPad, and that gap is why I ended up adding samples of my own.
An image is a grid of numbers
Everything starts with turning a picture into numbers. A letter in EMNIST is a 28×28 grid of pixels, and each pixel is a brightness from 0 to 255. So one letter is 784 numbers.
Before training, those numbers get divided by 255 so they sit between 0 and 1. Networks learn much more smoothly with small numbers, and this one line is called normalisation.
image = image.astype("float32") / 255.0 # 0–255 becomes 0.0–1.0
image = image.reshape(28, 28, 1) # height, width, one colour channelThat shape, (28, 28, 1), is a tensor, which is just the general word for a grid of numbers with any number of dimensions. A batch of 32 images is a tensor of shape (32, 28, 28, 1).
The answer for each image is a label. Letters become numbers too, 0 for a through 25 for z.
Two details about the data caught me out much later, so they're worth saying now. EMNIST stores its images transposed, so a raw A looks rotated and mirrored until you flip it back, and every image you feed the model has to be in the same orientation as the training data. And I started on the Letters split without thinking through what it meant to have A and a share one label in an app where children mostly write lowercase. I didn't take either of those seriously enough at the start, and both cost me later.
A neuron is a weighted sum
A neuron takes some numbers in, multiplies each by a weight, adds them up, adds one more number called a bias, and passes the result through an activation function.
inputs = [0.0, 0.8, 1.0]
weights = [0.5, -1.2, 0.9]
bias = 0.1
total = 0.0*0.5 + 0.8*-1.2 + 1.0*0.9 + 0.1 # = 0.04
output = relu(total) # = 0.04The weights decide how much each input matters, and a negative weight means "this input is evidence against". The bias shifts the whole thing up or down. Training a network means finding good values for these numbers. Nothing else in the network changes.
The activation function is there to add a bend. The most common one, ReLU, is almost insultingly simple: negative numbers become 0, everything else passes through unchanged. Without a bend like that, stacking layers would be pointless, because a chain of weighted sums is just one bigger weighted sum.
A layer is many neurons, and a network is many layers
A dense layer is a row of neurons that each look at every input. If 784 pixels go into a layer of 128 neurons, that's 784 × 128 weights plus 128 biases, and the layer's output is 128 numbers. In practice it's done as one matrix multiplication, which is why GPUs are so good at it.
Feed those 128 numbers into another layer, and then another, and you have a network. The early layers turn pixels into simple features. Later layers combine those into more useful ones. You never tell it what the features should be. Training finds them.
Softmax turns scores into a guess
The last layer has one neuron per answer, so 26 for the alphabet. Their raw outputs can be any numbers, which isn't much use. Softmax turns them into probabilities that are all positive and add up to 1.
scores = [2.0, 1.0, 0.1] # raw outputs for, say, a, b, c
probs = softmax(scores) # [0.659, 0.242, 0.099]It exponentiates each score and divides by the total, so the biggest score gets a large share and small differences get stretched. The model's prediction is whichever letter has the highest probability, and the probability itself is its confidence.
Loss measures how wrong a guess was
To improve, the network needs a single number that says how bad its guess was. For classification that's cross-entropy, which is the negative log of the probability given to the correct answer.
loss = -log(probs[correct_label])
# Correct answer got 0.95 → loss ≈ 0.05
# Correct answer got 0.66 → loss ≈ 0.42
# Correct answer got 0.01 → loss ≈ 4.6Being confidently wrong is punished far harder than being unsure. In Keras this is sparse_categorical_crossentropy. The "sparse" part means the labels are plain integers like 7, not 26-long lists of zeros with a single 1.
Gradient descent nudges every weight
Now the central trick. For every weight in the network, you can ask "if I nudged this weight up a tiny bit, would the loss go up or down, and by how much?" That rate of change is the weight's gradient.
If you know the gradient, improving is easy. Move each weight a small step in whichever direction makes the loss smaller.
new_weight = weight - learning_rate * gradient
# weight 0.5, gradient 0.2, learning rate 0.001
# new weight 0.4998The learning rate is the size of that step, and it's the setting people fiddle with most. Too big and the weights overshoot and bounce around. Too small and training takes forever.
Backpropagation finds all the gradients at once
A model can have hundreds of thousands of weights, so working out each gradient separately would be hopeless. Backpropagation gets them all in one pass by running backwards from the loss through every layer and using the chain rule from calculus. Each layer only needs the gradient from the layer after it to work out its own.
You never write this yourself. TensorFlow records every operation on the way forward and does the backward pass for you. But it's why a training step is always the same four things in a loop. Run a batch forward and get predictions. Compute the loss. Run backwards to get gradients. Update the weights.
Batches, epochs and the optimiser
You don't update the weights after every single image, and you don't wait for the whole dataset either. You go a batch at a time, commonly 32 images. The gradient is averaged across the batch, which makes each step less jumpy and lets the hardware do 32 images at once.
One full pass through the training data is an epoch. Training runs for many epochs, because each pass only moves the weights a little.
The optimiser is the thing that applies the updates. Plain gradient descent uses one learning rate for everything. Adam, which is what I used with a starting learning rate of 0.001, keeps a running memory of recent gradients for each weight and adapts the step size per weight. It's the default for good reason and it mostly just works.
Validation data keeps you honest
A network with enough weights can memorise its training data, getting every training image right while being useless on anything new. That's overfitting, and the only way to see it is to test on images the model has never trained on.
So the data gets split three ways. The training set is what the weights learn from. The validation set gets checked after every epoch, and you watch its accuracy to decide when to stop. The test set is held back until the very end and used once, to report a number you can trust.
The usual sign of overfitting is training accuracy climbing while validation accuracy stalls or drops. Early stopping watches for that and halts training, rolling back to the best epoch. One of my later training runs stopped after 29 epochs, and its best validation score had come at epoch 18.
Convolutions look at small patches
Everything so far would work on any data. Convolutional networks are what make images work well.
A dense layer treats the 784 pixels as unrelated numbers, with no idea which pixels are neighbours. A convolutional layer instead slides a small filter, usually 3×3, across the image. At each position it computes a weighted sum of those nine pixels, exactly like a neuron, and writes the result into a new grid called a feature map. The same nine weights are used at every position, so a filter that learns to spot a vertical edge will spot it anywhere in the image.
A 3×3 filter can't hang off the edge, so a 28×28 image gives a 26×26 feature map. A layer with 32 filters gives 32 feature maps, a tensor of shape (26, 26, 32).
The weights are counted per filter, and this is where I went wrong early on. A first layer of 32 filters over one input channel has 3 × 3 × 1 × 32 = 288 weights plus 32 biases, 320 in total. A second layer of 64 filters, each looking at all 32 feature maps from before, has 3 × 3 × 32 × 64 = 18,432 weights plus 64 biases. I once multiplied by the 64 twice, got over a million for that layer, and believed my model had about 1.4 million parameters. It had about 227,000. model.summary() prints the exact count for every layer, and I should have run it before reaching for a calculator.
Pooling shrinks the picture
After a convolution, a pooling layer shrinks each feature map by keeping only the largest value in every 2×2 square. A 26×26 map becomes 13×13.
That halves the work for the next layer, and it means a feature that moved one pixel to the left still produces roughly the same output. For handwriting, where nobody writes a letter in exactly the same spot twice, that tolerance matters a lot.
Stack convolution and pooling twice and the shapes go 28 → 26 → 13 → 11 → 5. At the end you flatten the 5 × 5 × 64 grid into 1,600 numbers and hand them to ordinary dense layers to make the final call.
Stopping a network from memorising
There are a handful of standard tricks for overfitting, and they all appear in the script below.
Dropout switches off a random half of a layer's neurons on every training step. No neuron can rely on any particular other one being there, so the network has to spread what it knows around. It's only active during training.
Batch normalisation rescales each layer's outputs to a steady range during training. It makes training faster and less sensitive to the starting learning rate.
Data augmentation makes up new training images by slightly rotating, shifting and zooming the real ones. I used rotations of up to 10 degrees, shifts of up to 10% and zoom between 90% and 110%. The model sees a slightly different version of each letter every epoch, which is about as close as you can get to collecting more handwriting without collecting more handwriting.
The whole script
That's everything. Here's a cut-down version of the kind of script I ended up with, and every line maps onto something above.
from tensorflow import keras
from tensorflow.keras import layers
model = keras.Sequential([
layers.Input(shape=(28, 28, 1)), # one normalised 28×28 image
layers.Conv2D(32, 3, activation="relu"), # 32 filters → (26, 26, 32)
layers.BatchNormalization(),
layers.MaxPooling2D(2), # → (13, 13, 32)
layers.Conv2D(64, 3, activation="relu"), # 64 filters → (11, 11, 64)
layers.BatchNormalization(),
layers.MaxPooling2D(2), # → (5, 5, 64)
layers.Flatten(), # → 1,600 numbers
layers.Dense(128, activation="relu"),
layers.Dropout(0.5), # off during prediction
layers.Dense(26, activation="softmax"), # 26 probabilities
])
model.compile(
optimizer=keras.optimizers.Adam(learning_rate=0.001),
loss="sparse_categorical_crossentropy", # labels are 0–25
metrics=["accuracy"],
)
model.summary() # check the parameter counts
model.fit(
x_train, y_train,
batch_size=32,
epochs=50, # upper limit
validation_data=(x_val, y_val),
callbacks=[keras.callbacks.EarlyStopping(
monitor="val_accuracy", patience=10, restore_best_weights=True,
)],
)
model.evaluate(x_test, y_test) # the one honest numbermodel.fit is the four-step loop from earlier, run over every batch in every epoch, with a validation check at the end of each epoch and early stopping watching it.
Understanding all of that didn't stop me making mistakes, though. The orientation problem I mentioned at the start came back to bite me ten months later, when I found my own handwriting samples had been going into the model rotated the wrong way all along. I knew orientation mattered. I just hadn't drawn the model's input to check, and that one's in the next post: eleven months teaching a CNN to read handwriting.