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 of shape :
The parameters are (), (16), (16) and : 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 for "gradient of the loss with respect to this quantity". Starting from the output:
Every weight gradient has the same form: (input to the layer) 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 , suited to ReLU) for and for the output layer. Biases start at zero. Why these scales matter is the subject of parameters and initialisation.
The full loop
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 () 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.
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, needs 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
yhas shape(B, 1)andphas shape(B,), thenp - yis a matrix, NumPy raises no error, and the loss is nonsense. Keep both one-dimensional, or check shapes withassert. - 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
- Count the parameters of a 784-128-64-10 MLP (for 28 by 28 images and 10 classes).
Answer
, , ; total .
- In
backward, why isdA1 = dH * (A1 > 0)and notdH * (H > 0)? Does it matter?
Answer
The ReLU derivative is 1 where its input is positive and 0 elsewhere. Since , exactly where , 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.
- Initialise all of to zero and to zero, and run the first example. What happens and why?
Answer
for every input, so for is , and , so gets zero gradient too. Only learns: the model predicts the base rate for everyone, accuracy about 0.5. Even with , 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?
- The whole loop must be rewritten
- Only the forward pass and the gradient computation; batching, updates, validation and checkpointing stay the same
- Only the learning rate
- The validation step is removed
In backpropagation, the gradient of a dense layer's weight matrix is…
- (gradient at the output) times (gradient at the output) transposed
- (input to the layer) transposed times (gradient at the layer's output)
- the layer's weights times the loss
- the activation's derivative alone
How many parameters does a 2-16-1 MLP with biases have?
- 32
- 48
- 65
- 33
Why does ReLU's backward pass multiply by the mask ?
- To regularise the network
- Because the derivative of is 1 for and 0 for
- To keep gradients positive
- Because the sigmoid requires it