Chapter 15 — Implementation: Neural Networks from Scratch and in PyTorch
We build a neural network from scratch in NumPy, check that our backpropagation is right, and then do the same work in PyTorch on handwritten digits.
Contents
The perceptron, and why it fails on XOR
A multilayer perceptron in NumPy, with backpropagation
Gradient checking: is backpropagation right?
Learning a curved boundary
Optimisers compared: SGD, momentum, Adam
PyTorch: handwritten digits, overfitting, dropout and early stopping
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import make_moons, load_digits
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
np.random.seed(0); torch.manual_seed(0)
plt.rcParams['figure.figsize'] = (7, 4)1. The Perceptron¶
def train_perceptron(X, y, eta=0.1, epochs=20):
w, b = np.zeros(X.shape[1]), 0.0
for _ in range(epochs):
for x, t in zip(X, y):
pred = int(w @ x + b > 0)
w += eta * (t - pred) * x # the perceptron rule: only mistakes change w
b += eta * (t - pred)
return w, b
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
for name, y in [('AND', np.array([0, 0, 0, 1])), ('OR', np.array([0, 1, 1, 1])), ('XOR', np.array([0, 1, 1, 0]))]:
w, b = train_perceptron(X, y)
pred = (X @ w + b > 0).astype(int)
print(f'{name:3}: predictions {pred}, targets {y} -> {"learned" if (pred == y).all() else "FAILED"}')AND: predictions [0 0 0 1], targets [0 0 0 1] -> learned
OR : predictions [0 1 1 1], targets [0 1 1 1] -> learned
XOR: predictions [1 1 0 0], targets [0 1 1 0] -> FAILED
AND and OR are linearly separable; XOR is not, and the perceptron keeps cycling forever.
2. A Multilayer Perceptron in NumPy¶
A network with one hidden ReLU layer and a sigmoid output, trained with binary cross-entropy. The backward method is a direct transcription of the chapter’s equations, for a whole batch at once (examples are rows).
class MLP:
def __init__(self, n_in, n_hidden, seed=0):
rng = np.random.default_rng(seed)
self.W1 = rng.normal(0, np.sqrt(2 / n_in), (n_in, n_hidden)) # He initialisation for ReLU
self.b1 = np.zeros(n_hidden)
self.W2 = rng.normal(0, np.sqrt(1 / n_hidden), (n_hidden, 1))
self.b2 = np.zeros(1)
def forward(self, X):
self.X = X
self.Z1 = X @ self.W1 + self.b1
self.A1 = np.maximum(0, self.Z1) # ReLU
self.Z2 = self.A1 @ self.W2 + self.b2
self.P = 1 / (1 + np.exp(-self.Z2)) # sigmoid
return self.P.ravel()
def loss(self, y):
p = np.clip(self.P.ravel(), 1e-12, 1 - 1e-12)
return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
def backward(self, y):
n = len(y)
d2 = (self.P - y.reshape(-1, 1)) / n # sigmoid + cross-entropy: p - y
self.gW2, self.gb2 = self.A1.T @ d2, d2.sum(0)
d1 = (d2 @ self.W2.T) * (self.Z1 > 0) # send the error back, times ReLU'
self.gW1, self.gb1 = self.X.T @ d1, d1.sum(0)
def params_and_grads(self):
return [(self.W1, self.gW1), (self.b1, self.gb1), (self.W2, self.gW2), (self.b2, self.gb2)]
def train(model, X, y, eta=0.5, epochs=2000):
losses = []
for _ in range(epochs):
model.forward(X); losses.append(model.loss(y)); model.backward(y)
for p, g in model.params_and_grads():
p -= eta * g
return losses
Xx = np.array([[0, 0], [0, 1], [1, 0], [1, 1.]]); yx = np.array([0, 1, 1, 0.])
net = MLP(2, 4, seed=1)
losses = train(net, Xx, yx, eta=0.5, epochs=3000)
print('XOR predictions:', net.forward(Xx).round(3))
plt.plot(losses); plt.xlabel('epoch'); plt.ylabel('cross-entropy'); plt.title('A hidden layer learns XOR'); plt.show()XOR predictions: [0.001 1. 1. 0. ]

3. Gradient Checking¶
Backpropagation bugs are silent: the network trains, just badly. We compare each gradient with a numerical estimate .
def gradient_check(model, X, y, eps=1e-6):
model.forward(X); model.backward(y)
worst = 0
for p, g in model.params_and_grads():
for idx in np.ndindex(p.shape):
old = p[idx]
p[idx] = old + eps; model.forward(X); lp = model.loss(y)
p[idx] = old - eps; model.forward(X); lm = model.loss(y)
p[idx] = old
numeric = (lp - lm) / (2 * eps)
worst = max(worst, abs(numeric - g[idx]) / max(1e-8, abs(numeric) + abs(g[idx])))
return worst
Xc, yc = make_moons(20, noise=0.2, random_state=0)
print(f'largest relative difference: {gradient_check(MLP(2, 5, seed=3), Xc, yc.astype(float)):.2e} (below 1e-6: backpropagation is right)')largest relative difference: 1.04e-08 (below 1e-6: backpropagation is right)
4. Learning a Curved Boundary¶
Logistic regression can only draw a line through the two interleaving “moons”; a small MLP bends its boundary around them.
Xm, ym = make_moons(400, noise=0.2, random_state=0)
net = MLP(2, 16, seed=0)
train(net, Xm, ym.astype(float), eta=0.5, epochs=3000)
print(f'training accuracy: {np.mean((net.forward(Xm) > 0.5) == ym):.3f}')
xx, yy = np.meshgrid(np.linspace(-1.5, 2.5, 250), np.linspace(-1, 1.5, 250))
zz = net.forward(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
plt.contourf(xx, yy, zz, levels=[0, 0.5, 1], alpha=0.25, cmap='coolwarm')
plt.scatter(Xm[:, 0], Xm[:, 1], c=ym, cmap='coolwarm', s=10); plt.title('The MLP\'s decision boundary'); plt.show()training accuracy: 0.968

5. Optimisers Compared¶
The same network and data, trained with three optimisers written in a few lines each.
def train_with(optimizer, epochs=300, eta=0.05, beta=0.9, b1=0.9, b2=0.999):
net = MLP(2, 16, seed=0)
state = {}
losses = []
for t in range(1, epochs + 1):
net.forward(Xm); losses.append(net.loss(ym)); net.backward(ym.astype(float))
for i, (p, g) in enumerate(net.params_and_grads()):
if optimizer == 'SGD':
p -= eta * g
elif optimizer == 'momentum':
v = state[i] = beta * state.get(i, 0) + g
p -= eta * v
else: # Adam
m, s = state.get(i, (0, 0))
m, s = b1 * m + (1 - b1) * g, b2 * s + (1 - b2) * g ** 2
state[i] = (m, s)
p -= 0.01 * (m / (1 - b1 ** t)) / (np.sqrt(s / (1 - b2 ** t)) + 1e-8)
return losses
for name in ['SGD', 'momentum', 'Adam']:
plt.plot(train_with(name), label=name)
plt.xlabel('epoch'); plt.ylabel('loss'); plt.legend(); plt.title('Momentum and Adam reach a low loss sooner'); plt.show()
6. PyTorch: Handwritten Digits¶
scikit-learn’s digits dataset: 1 797 images of 8×8 pixels, digits 0–9. Small enough to train in seconds on a laptop CPU.
digits = load_digits()
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.2, stratify=digits.target, random_state=0)
X_train, X_valid, y_train, y_valid = train_test_split(X_train, y_train, test_size=0.2, stratify=y_train, random_state=0)
scaler = StandardScaler().fit(X_train)
to_t = lambda X, y: (torch.tensor(scaler.transform(X), dtype=torch.float32), torch.tensor(y))
train_ds, valid_ds, test_ds = TensorDataset(*to_t(X_train, y_train)), TensorDataset(*to_t(X_valid, y_valid)), TensorDataset(*to_t(X_test, y_test))
print(len(train_ds), 'training,', len(valid_ds), 'validation,', len(test_ds), 'test images')
fig, axes = plt.subplots(1, 8, figsize=(10, 1.6))
for ax, img, lab in zip(axes, digits.images, digits.target):
ax.imshow(img, cmap='gray_r'); ax.set_title(lab); ax.axis('off')
plt.show()1149 training, 288 validation, 360 test images

Autograd computes the same gradients as our hand-written backpropagation:
x = torch.tensor([1.0, 0.0])
W1 = torch.tensor([[0.5, -0.4], [0.3, 0.8]], requires_grad=True); b1 = torch.tensor([0.1, -0.1], requires_grad=True)
W2 = torch.tensor([0.7, -0.6], requires_grad=True); b2 = torch.tensor(0.2, requires_grad=True)
y_hat = torch.sigmoid(W2 @ torch.sigmoid(W1 @ x + b1) + b2)
loss = 0.5 * (y_hat - 1) ** 2
loss.backward()
print(f'y_hat = {y_hat.item():.3f}, loss = {loss.item():.4f}')
print('dL/dW2 =', W2.grad.numpy().round(4), ' dL/dW1 =', W1.grad.numpy().round(4)[:, 0], '(first column; the second is 0)')y_hat = 0.580, loss = 0.0883
dL/dW2 = [-0.0661 -0.0563] dL/dW1 = [-0.0164 0.0152] (first column; the second is 0)
These are exactly the numbers of the chapter’s worked example. Now a real training loop, with a validation curve:
def fit(model, epochs=60, lr=1e-3, weight_decay=0.0, patience=None):
loader = DataLoader(train_ds, batch_size=64, shuffle=True)
opt = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)
loss_fn = nn.CrossEntropyLoss()
history, best, best_state, wait = {'train': [], 'valid': []}, float('inf'), None, 0
for epoch in range(epochs):
model.train()
for xb, yb in loader:
loss = loss_fn(model(xb), yb)
opt.zero_grad(); loss.backward(); opt.step()
model.eval()
with torch.no_grad():
history['train'].append(loss_fn(model(train_ds.tensors[0]), train_ds.tensors[1]).item())
v = loss_fn(model(valid_ds.tensors[0]), valid_ds.tensors[1]).item()
history['valid'].append(v)
if v < best:
best, best_state, wait = v, {k: t.clone() for k, t in model.state_dict().items()}, 0
elif patience is not None:
wait += 1
if wait >= patience:
break
if patience is not None:
model.load_state_dict(best_state) # early stopping: keep the best weights
return history
def accuracy(model, ds):
model.eval()
with torch.no_grad():
return (model(ds.tensors[0]).argmax(1) == ds.tensors[1]).float().mean().item()
torch.manual_seed(0)
big = nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Linear(256, 256), nn.ReLU(), nn.Linear(256, 10))
h_big = fit(big, epochs=80)
torch.manual_seed(0)
reg = nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Dropout(0.3), nn.Linear(256, 256), nn.ReLU(), nn.Dropout(0.3), nn.Linear(256, 10))
h_reg = fit(reg, epochs=80, weight_decay=1e-3, patience=20)
fig, axes = plt.subplots(1, 2, figsize=(12, 3.8), sharey=True)
for ax, h, title in [(axes[0], h_big, 'no regularisation'), (axes[1], h_reg, 'dropout + weight decay + early stopping')]:
ax.plot(h['train'], label='training'); ax.plot(h['valid'], label='validation'); ax.set_title(title); ax.set_xlabel('epoch'); ax.legend()
axes[0].set_ylabel('cross-entropy'); plt.tight_layout(); plt.show()
print(f'validation accuracy: plain {accuracy(big, valid_ds):.3f} regularised {accuracy(reg, valid_ds):.3f}')
validation accuracy: plain 0.969 regularised 0.983
Without regularisation, the training loss goes to almost zero while the validation loss creeps back up: overfitting. With dropout, weight decay and early stopping, the validation loss stays low and the validation accuracy is higher. Finally, the test set, once:
print(f'test accuracy of the regularised network: {accuracy(reg, test_ds):.3f}')
reg.eval()
with torch.no_grad():
pred = reg(test_ds.tensors[0]).argmax(1).numpy()
wrong = np.where(pred != y_test)[0][:6]
fig, axes = plt.subplots(1, max(1, len(wrong)), figsize=(8, 1.8))
for ax, i in zip(np.atleast_1d(axes), wrong):
ax.imshow(X_test[i].reshape(8, 8), cmap='gray_r'); ax.set_title(f'{y_test[i]} → {pred[i]}'); ax.axis('off')
plt.suptitle('Some mistakes: true → predicted', y=1.1); plt.show()test accuracy of the regularised network: 0.975

Key Takeaways¶
One neuron draws one line; a hidden layer lets the network combine lines into any shape.
Backpropagation is the chain rule run backwards; gradient checking proves an implementation right.
Momentum and Adam reach a low loss much faster than plain SGD.
PyTorch’s autograd gives the same gradients as the hand-derived equations, and the training loop is always: forward, loss,
zero_grad,backward,step.Watch the validation curve: dropout, weight decay and early stopping stop the network memorising.