Pulse Data Hub

Neural Networks in Python: Build One from Scratch, Tested

Neural Networks in Python: Build One from Scratch, Tested

Neural networks in Python do not need a big framework to understand. In this guide we write a small network in plain NumPy, train it on 1,797 real handwritten digits, and test what happens when you change its size, learning rate and starting weights. All numbers are measured (NumPy 2.5.3, scikit-learn 1.9.1), and we say where a result is only one run.

Bar chart of test accuracy by hidden units: 2 units 9.8%, 4 units 30.4%, 8 units 95.6%, 16 units 97.1%, 32 units 97.6%, 64 units 97.8%, 128 units 97.3%
Too few hidden units and the network cannot learn the task at all; after 16 the gains are small.

What a neural network is

A network is layers of simple functions. Each layer multiplies its input by a weight matrix, adds a bias, and applies a non-linear function such as ReLU (replace negatives with zero). Training repeatedly nudges the weights downhill on the error, using gradients computed by backpropagation. Our network has 64 inputs (the 8×8 pixels), one hidden layer and 10 outputs, one per digit.

The data and the baseline to beat

The digits set from scikit-learn (UCI optical digits) has 1,797 images; we used 1,347 for training and 450 for testing, with pixels divided by 16. A plain logistic regression, which has no hidden layer, scores 0.969 on the test images. A neural network has to beat that to be worth the trouble.

The network in about 25 lines

import numpy as np

def train(Xtr, ytr, Xte, yte, hidden=32, lr=0.5, epochs=60, seed=0):
    r = np.random.RandomState(seed); n = len(Xtr); Y = np.eye(10)[ytr]
    W1 = r.randn(64, hidden) * np.sqrt(2 / 64); b1 = np.zeros(hidden)
    W2 = r.randn(hidden, 10) * np.sqrt(2 / hidden); b2 = np.zeros(10)
    for epoch in range(epochs):
        order = r.permutation(n)
        for i in range(0, n, 32):                  # mini-batches of 32
            j = order[i:i + 32]; x = Xtr[j]
            z = x @ W1 + b1; a = np.maximum(z, 0)  # hidden layer, ReLU
            o = a @ W2 + b2; o -= o.max(1, keepdims=True)
            p = np.exp(o) / np.exp(o).sum(1, keepdims=True)   # softmax
            d = (p - Y[j]) / len(j)                # gradient of cross-entropy
            gW2 = a.T @ d; gb2 = d.sum(0)
            dz = (d @ W2.T) * (z > 0)              # backpropagate through ReLU
            gW1 = x.T @ dz; gb1 = dz.sum(0)
            W1 -= lr * gW1; b1 -= lr * gb1; W2 -= lr * gW2; b2 -= lr * gb2
    z = Xte @ W1 + b1; a = np.maximum(z, 0)
    return ((a @ W2 + b2).argmax(1) == yte).mean()

With 32 hidden units (2,410 weights and biases) the test accuracy after 1, 5, 20 and 60 passes over the data was 0.262, 0.949, 0.973 and 0.976. Training took 0.13 seconds. That beats logistic regression by about 0.7 points, which is 3 images out of 450, so on this easy dataset a neural network is not dramatically better. Across five random seeds the final score ranged from 0.969 to 0.978, so differences of half a point are noise. For reference, scikit-learn’s MLPClassifier with 32 hidden units scored 0.973 (it hit its 300-iteration limit before converging).

Experiment 1: how many hidden units?

Hidden unitsParametersTest accuracy
21600.098
43100.304
86100.956
161,2100.971
322,4100.976
644,8100.978
1289,6100.973

With 2 units the network scored 0.098, no better than guessing among 10 digits, because 2 numbers cannot carry enough information about a digit. The jump between 4 and 8 units is dramatic, then returns shrink; 128 units did not beat 64.

Experiment 2: the learning rate

Learning rateTest accuracy after 60 epochs
0.0010.698
0.010.936
0.10.976
0.50.976
20.100
100.100

Too small and training is slow (0.698 after 60 epochs). Too large and it diverges (0.100, chance level). Anything from 0.1 to 0.5 worked. This is the parameter to check first when a network will not train.

Experiment 3: activation and starting weights

Replacing ReLU with sigmoid still reached 0.976 after 60 epochs, but was slower early on (0.933 versus 0.949 after 5). Starting with tiny weights (1e-4 instead of scaled random values) delayed learning, scoring 0.100 after the first epoch and ending at 0.971. Initialization matters mainly for how quickly training gets going.

Where TensorFlow and PyTorch fit

Frameworks do what we wrote by hand, automatically and on GPUs, which you need for images, text and large data. For a worked framework example, see our TensorFlow tutorial, and CNNs explained for images. For small tabular data, simpler models are often as good: compare random forests and logistic regression. The official scikit-learn neural network documentation describes the built-in MLP.

Limits of this test

One easy 8×8 dataset, one hidden layer, a single train/test split, and a fixed 60 epochs without early stopping. We did not test dropout, deeper networks or other optimizers, and results on harder data will differ.

FAQ

How many hidden layers do I need?

One was enough here. More layers help on harder problems such as images and language; start small and add only if validation accuracy improves.

Why did my network stay at chance accuracy?

In our tests two causes did it: too few hidden units (2 units gave 0.098) and a learning rate that was too high (2 and 10 gave 0.100).

Is a neural network better than logistic regression?

Not always. Here it was about 0.7 points better, a few images. Always compare with a simple baseline.

Do I need a GPU?

Not for this size: training took 0.13 seconds on a CPU.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights