TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › A Tiny MLP Trained in NumPy

A Tiny MLP Trained in NumPy

Logistic regression draws one straight line through the data. On the two interleaved half-moons below no straight line separates the classes, so the model needs to bend its boundary. A multilayer perceptron (MLP) does that by putting a hidden layer of nonlinear units between the input and the output. The training loop does not change at all: batch, forward, loss, backprop, update, validate, keep the best. Only two functions change, the forward pass and the gradient, and the gradient now comes from backpropagation through two layers.

This lesson builds a 2-16-1 network (2 inputs, 16 hidden ReLU units, 1 sigmoid output) in about 40 lines of NumPy. The next lesson trains the same network in PyTorch and gets the same numbers.

The network

For a batch XX of shape B×2B \times 2:

A1=XW1+b1B×16, pre-activationsH=max⁡(0,A1)ReLU, elementwisez=Hw2+b2B×1, the logitp^=σ(z)probability of class 1\begin{aligned} A_1 &= X W_1 + \mathbf{b}_1 && B \times 16,\ \text{pre-activations} \\ H &= \max(0, A_1) && \text{ReLU, elementwise} \\ \mathbf{z} &= H \mathbf{w}_2 + b_2 && B \times 1,\ \text{the logit} \\ \hat{\mathbf{p}} &= \sigma(\mathbf{z}) && \text{probability of class 1} \end{aligned}

The parameters are W1W_1 (2×162 \times 16), b1\mathbf{b}_1 (16), w2\mathbf{w}_2 (16) and b2b_2: 32+16+16+1=6532 + 16 + 16 + 1 = 65 numbers. The loss is the mean binary cross-entropy, exactly as for logistic regression.

Backpropagation through two layers

Backpropagation is the chain rule applied from the loss backwards, reusing each intermediate result once. Write δ\delta for "gradient of the loss with respect to this quantity". Starting from the output:

δz=1B(p^−y)sigmoid + cross-entropy, as before∇w2L=H⊤δz,∂L∂b2=∑iδziδH=δzw2⊤B×16δA1=δH⊙1[A1>0]ReLU passes gradient only where it was active∇W1L=X⊤δA1,∇b1L=∑i(δA1)i,:\begin{aligned} \delta_{\mathbf{z}} &= \frac{1}{B} (\hat{\mathbf{p}} - \mathbf{y}) && \text{sigmoid + cross-entropy, as before} \\ \nabla_{\mathbf{w}_2} L &= H^\top \delta_{\mathbf{z}}, \quad \frac{\partial L}{\partial b_2} = \textstyle\sum_i \delta_{z_i} \\ \delta_H &= \delta_{\mathbf{z}} \mathbf{w}_2^\top && B \times 16 \\ \delta_{A_1} &= \delta_H \odot \mathbb{1}[A_1 > 0] && \text{ReLU passes gradient only where it was active} \\ \nabla_{W_1} L &= X^\top \delta_{A_1}, \quad \nabla_{\mathbf{b}_1} L = \textstyle\sum_i (\delta_{A_1})_{i,:} \end{aligned}

Every weight gradient has the same form: (input to the layer)⊤^\top times (gradient at the layer's output). The general derivation is in Backpropagation Through an MLP; the lesson on forward propagation, loss and backpropagation checks it numerically.

Initialisation

The weights cannot start at zero: all 16 hidden units would compute the same thing and receive the same gradient forever. They start small and random, here with He initialisation (standard deviation 2/fan-in\sqrt{2/\text{fan-in}}, suited to ReLU) for W1W_1 and 1/16\sqrt{1/16} for the output layer. Biases start at zero. Why these scales matter is the subject of parameters and initialisation.

The full loop

python · try it yourself
import numpy as np
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split

X, y = make_moons(n_samples=600, noise=0.25, random_state=0)
X_tr, X_tmp, y_tr, y_tmp = train_test_split(X, y, test_size=200, random_state=0)
X_val, X_te, y_val, y_te = train_test_split(X_tmp, y_tmp, test_size=100, random_state=0)
mu, sd = X_tr.mean(axis=0), X_tr.std(axis=0)           # standardise with training statistics
X_tr, X_val, X_te = (X_tr - mu) / sd, (X_val - mu) / sd, (X_te - mu) / sd

def init(hidden, rng):
    return {"W1": rng.normal(0, np.sqrt(2 / 2), (2, hidden)), "b1": np.zeros(hidden),
            "w2": rng.normal(0, np.sqrt(1 / hidden), hidden), "b2": 0.0}

def forward(P, X):
    A1 = X @ P["W1"] + P["b1"]
    H = np.maximum(0, A1)
    p = 1 / (1 + np.exp(-(H @ P["w2"] + P["b2"])))
    return p, (A1, H)

def bce(p, y, eps=1e-12):
    p = np.clip(p, eps, 1 - eps)
    return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))

def backward(P, X, y, p, cache):
    A1, H = cache
    dz = (p - y) / len(y)
    dH = np.outer(dz, P["w2"])
    dA1 = dH * (A1 > 0)
    return {"W1": X.T @ dA1, "b1": dA1.sum(axis=0), "w2": H.T @ dz, "b2": dz.sum()}

def evaluate(P, X, y):
    p, _ = forward(P, X)
    return bce(p, y), np.mean((p >= 0.5) == y)

rng = np.random.default_rng(0)
P = init(16, rng)
print("parameters:", sum(np.size(v) for v in P.values()))
lr, batch_size, best = 0.3, 32, {"loss": np.inf}
for epoch in range(1, 151):
    order = rng.permutation(len(y_tr))
    for start in range(0, len(y_tr), batch_size):
        idx = order[start:start + batch_size]
        p, cache = forward(P, X_tr[idx])                         # forward
        grads = backward(P, X_tr[idx], y_tr[idx], p, cache)     # backprop
        P = {k: P[k] - lr * grads[k] for k in P}                 # update (new dict)
    tr_loss, tr_acc = evaluate(P, X_tr, y_tr)
    val_loss, val_acc = evaluate(P, X_val, y_val)                # validate
    if val_loss < best["loss"]:
        best = {"loss": val_loss, "epoch": epoch, "P": P}         # keep the best
    if epoch in (1, 10, 30, 60, 100, 150):
        print(f"epoch {epoch:3d}  train loss {tr_loss:.4f} acc {tr_acc:.3f}   val loss {val_loss:.4f} acc {val_acc:.3f}")

print("best epoch", best["epoch"], " val loss", round(best["loss"], 4))
te_loss, te_acc = evaluate(best["P"], X_te, y_te)
print(f"test (once): loss {te_loss:.4f}  accuracy {te_acc:.3f}")
parameters: 65
epoch   1  train loss 0.3101 acc 0.882   val loss 0.3195 acc 0.880
epoch  10  train loss 0.2370 acc 0.907   val loss 0.3028 acc 0.880
epoch  30  train loss 0.1596 acc 0.938   val loss 0.2148 acc 0.890
epoch  60  train loss 0.1220 acc 0.955   val loss 0.1889 acc 0.910
epoch 100  train loss 0.1119 acc 0.955   val loss 0.2022 acc 0.900
epoch 150  train loss 0.1089 acc 0.958   val loss 0.1871 acc 0.920
best epoch 145  val loss 0.1837
test (once): loss 0.2635  accuracy 0.920

The data: 600 points, 400 for training, 100 for validation and 100 for the final test, standardised with the training mean and standard deviation. With 13 batches per epoch, 150 epochs are 1950 updates.

  • The loss keeps falling, the accuracy moves in steps. Training loss drops from 0.3101 after the first epoch to 0.1089 after the last; validation accuracy climbs from 0.880 to 0.920 in steps of 0.01, one point of 100.
  • Validation is noisy. The validation loss was lower at epoch 60 (0.1889) than at epoch 100 (0.2022) and then went down again. A loop that stopped at the first increase would have quit too early, which is why early stopping uses a patience.
  • The best epoch was 145 (validation loss 0.1837). The test loss of that checkpoint is higher, 0.2635, at the same accuracy 0.920: 100 test points is a small sample, and the checkpoint was selected on validation data.
  • Train and validation stay close (0.958 against 0.920 accuracy). With 65 parameters and 400 points the network has little room to memorise; the moons' noise (σ=0.25\sigma = 0.25) makes some points impossible to classify.

What the hidden layer buys

The same loop with three model sizes: no hidden layer (that is logistic regression), 2 hidden units and 16 hidden units. The hidden-layer-free model uses the logistic-regression forward pass; everything else is identical.

python · try it yourself
import numpy as np
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split

X, y = make_moons(n_samples=600, noise=0.25, random_state=0)
X_tr, X_tmp, y_tr, y_tmp = train_test_split(X, y, test_size=200, random_state=0)
X_val, _, y_val, _ = train_test_split(X_tmp, y_tmp, test_size=100, random_state=0)
mu, sd = X_tr.mean(axis=0), X_tr.std(axis=0)
X_tr, X_val = (X_tr - mu) / sd, (X_val - mu) / sd

def run(hidden, epochs=150, lr=0.3, seed=0):
    rng = np.random.default_rng(seed)
    if hidden == 0:                                   # logistic regression: a linear model
        P = {"w": np.zeros(2), "b": 0.0}
        fwd = lambda P, X: (1 / (1 + np.exp(-(X @ P["w"] + P["b"]))), None)
        def bwd(P, X, y, p, c):
            d = (p - y) / len(y)
            return {"w": X.T @ d, "b": d.sum()}
    else:
        P = {"W1": rng.normal(0, 1, (2, hidden)), "b1": np.zeros(hidden),
             "w2": rng.normal(0, np.sqrt(1 / hidden), hidden), "b2": 0.0}
        def fwd(P, X):
            A1 = X @ P["W1"] + P["b1"]
            H = np.maximum(0, A1)
            return 1 / (1 + np.exp(-(H @ P["w2"] + P["b2"]))), (A1, H)
        def bwd(P, X, y, p, c):
            A1, H = c
            dz = (p - y) / len(y)
            dA1 = np.outer(dz, P["w2"]) * (A1 > 0)
            return {"W1": X.T @ dA1, "b1": dA1.sum(axis=0), "w2": H.T @ dz, "b2": dz.sum()}
    for epoch in range(epochs):
        order = rng.permutation(len(y_tr))
        for s in range(0, len(y_tr), 32):
            idx = order[s:s + 32]
            p, c = fwd(P, X_tr[idx])
            g = bwd(P, X_tr[idx], y_tr[idx], p, c)
            P = {k: P[k] - lr * g[k] for k in P}
    acc = lambda X, y: np.mean((fwd(P, X)[0] >= 0.5) == y)
    n_par = sum(np.size(v) for v in P.values())
    print(f"hidden {hidden:2d}  parameters {n_par:3d}  train acc {acc(X_tr, y_tr):.3f}  val acc {acc(X_val, y_val):.3f}")

for hidden in (0, 2, 16):
    run(hidden)
hidden  0  parameters   3  train acc 0.882  val acc 0.880
hidden  2  parameters   9  train acc 0.887  val acc 0.880
hidden 16  parameters  65  train acc 0.958  val acc 0.920

The linear model and the 2-unit network both stop at 0.880 validation accuracy: a straight line, or the few straight pieces that two ReLU units can join, cannot follow the moons. Sixteen hidden units reach 0.920. The 16-unit run is the same as the first example (same seed, same initial weights, same batch order), so its numbers match: the loop is deterministic, which is exactly what you want when you compare models.

Pitfalls

  • Overwriting a parameter before its gradient is used. In backprop, δH\delta_H needs w2\mathbf{w}_2 before the update. Compute all gradients first, then update all parameters, as the loop does with a new dictionary.
  • Shape bugs that broadcast silently. If y has shape (B, 1) and p has shape (B,), then p - y is a B×BB \times B matrix, NumPy raises no error, and the loss is nonsense. Keep both one-dimensional, or check shapes with assert.
  • Dead ReLUs. A hidden unit whose pre-activation is negative for every input gets zero gradient and never recovers. A learning rate that is too large makes this more likely.
  • Reading the best epoch as a fact about the model. The best epoch depends on the seed, the learning rate and the batch size. It tells you when to stop this run, not a property of the data.

Practice

  1. Count the parameters of a 784-128-64-10 MLP (for 28 by 28 images and 10 classes).
Answer

784⋅128+128=100480784 \cdot 128 + 128 = 100480, 128⋅64+64=8256128 \cdot 64 + 64 = 8256, 64⋅10+10=65064 \cdot 10 + 10 = 650; total 109386109386.

  1. In backward, why is dA1 = dH * (A1 > 0) and not dH * (H > 0)? Does it matter?
Answer

The ReLU derivative is 1 where its input A1A_1 is positive and 0 elsewhere. Since H=max⁡(0,A1)H = \max(0, A_1), H>0H > 0 exactly where A1>0A_1 > 0, so both give the same mask. Using the pre-activation states the rule directly, and it also works for activations like leaky ReLU where the output is never exactly zero.

  1. Initialise all of W1W_1 to zero and w2\mathbf{w}_2 to zero, and run the first example. What happens and why?
Answer

H=0H = 0 for every input, so δ\delta for w2\mathbf{w}_2 is H⊤δz=0H^\top \delta_{\mathbf{z}} = 0, and δH=δzw2⊤=0\delta_H = \delta_{\mathbf{z}} \mathbf{w}_2^\top = 0, so W1W_1 gets zero gradient too. Only b2b_2 learns: the model predicts the base rate for everyone, accuracy about 0.5. Even with w2≠0\mathbf{w}_2 \ne 0, identical hidden units would stay identical (the symmetry problem).

Test yourself

What changes in the training loop when you switch from logistic regression to an MLP?

  1. The whole loop must be rewritten
  2. Only the forward pass and the gradient computation; batching, updates, validation and checkpointing stay the same
  3. Only the learning rate
  4. The validation step is removed

In backpropagation, the gradient of a dense layer's weight matrix is…

  1. (gradient at the output) times (gradient at the output) transposed
  2. (input to the layer) transposed times (gradient at the layer's output)
  3. the layer's weights times the loss
  4. the activation's derivative alone

How many parameters does a 2-16-1 MLP with biases have?

  1. 32
  2. 48
  3. 65
  4. 33

Why does ReLU's backward pass multiply by the mask 1[A1>0]\mathbb{1}[A_1 > 0]?

  1. To regularise the network
  2. Because the derivative of max⁡(0,a)\max(0, a) is 1 for a>0a > 0 and 0 for a<0a < 0
  3. To keep gradients positive
  4. Because the sigmoid requires it