Lesson 1.8 — Building a Neural Network from Scratch
Can you build the whole loop yourself?
This lesson integrates the first seven lessons. You will not call a prebuilt model. You will write the affine layers, the hidden activation, the mean-squared-error loss and every parameter gradient, then train a two-layer network to imitate a nonlinear discrete dynamical system.
Input
Robot state x and control u form a feature vector. A batch stacks independent samples into a matrix.
Hidden representation
Each hidden neuron applies an affine transform, then a nonlinear activation. Width H is a design choice.
Output
Predict the next state. A regression head is linear; no activation is applied after the last affine layer.
The seven labs in this lesson
| Lab | What to inspect |
|---|---|
| 01 Nonlinearity | How activation changes the shape of the learned function |
| 02 Forward | The feature axes at every stage |
| 03 Gradient check | Analytic gradients compared with finite differences |
| 04 Training step | The moment parameters change |
| 05 Mini-batches | How batches cover the training set in one epoch |
| 06 Training | The effect of one hyperparameter at a time |
| 07 Rollout | How the next input depends on the evaluation mode |
Scope. The browser labs run real JavaScript arithmetic on a small synthetic system, not PyTorch. The Python blocks are complete enough to reproduce the same experiment locally. This teaching model is not a certified controller and must not be deployed on real hardware.
Why do we need a hidden activation?
If φ is the identity, the two layers collapse algebraically:
The composition is still one affine transformation. Depth without activation buys no nonlinear fitting power. Move the weights and the activation in the playground below and compare the green network with the dashed affine curve that shares the same weights.
Nonlinearity Playground
import numpy as np
x = 0.7
z = np.array([1.5*x + 0.5, -0.9*x + 0.2])
a = np.tanh(z)
print(a @ np.array([1.2, -0.8]) + 0.1)
Where the nonlinearity enters. The hidden activation lets the input–output function bend. The final affine layer combines the resulting features and produces a continuous next-state prediction.
From input tensor to scalar loss
For a batch of B samples, two input features and hidden width H:
Weight layout. The NumPy code in this lesson stores weights as
(in, out) so that a batch is written X @ W1. PyTorch
nn.Linear stores weight as (out, in); copying
parameters between the two requires a transpose.
The inspector below fixes H = 2 and a four-sample toy dataset so that every intermediate value fits on screen. The training experiment later uses H = 12.
Batched MLP Forward Inspector
| i | X | Z | A | ŷ | target | e² |
|---|---|---|---|---|---|---|
| 0 | (1, 0.5) | — | — | — | 1.1 | — |
| 1 | (-0.5, 1) | — | — | — | -0.2 | — |
| 2 | (0.2, -0.8) | — | — | — | 0.4 | — |
import numpy as np
# X shape (3, 2); W1 shape (2, 2)
X = np.array([[1, 0.5], [-0.5, 1], [0.2, -0.8]])
W1 = np.array([[0.7, -0.4], [0.3, 0.8]])
b1 = np.array([0.1, -0.2])
W2 = np.array([[0.9], [-0.7]])
b2 = np.array([0.05])
Z = X @ W1 + b1
A = np.tanh(Z)
Yhat = A @ W2 + b2
print(Z, A, Yhat)
Shape ledger · B = 16, H = 12
| Quantity | Formula | Shape |
|---|---|---|
Input X | batch × features | (16, 2) |
Weights W1 | features × hidden | (2, 12) |
Bias b1 | hidden | (12,) |
Pre-activation Z | batch × hidden | (16, 12) |
Activation A | batch × hidden | (16, 12) |
Weights W2 | hidden × output | (12, 1) |
Prediction Ŷ | batch × output | (16, 1) |
Loss L | scalar | () |
Bias broadcasting. The bias vector is added to every row of the batch. That is why one bias gradient sums contributions over all samples, while a weight gradient is a matrix product between the input and the upstream gradient.
Derive every parameter gradient
Gradient Flow & Numerical Check
| Parameter | Value | Analytic | Central FD | abs error | relative error |
|---|---|---|---|---|---|
W1[0,0] | 0.7 | — | — | — | — |
W1[0,1] | -0.4 | — | — | — | — |
W1[1,0] | 0.3 | — | — | — | — |
W1[1,1] | 0.8 | — | — | — | — |
b1[0] | 0.1 | — | — | — | — |
b1[1] | -0.2 | — | — | — | — |
W2[0,0] | 0.9 | — | — | — | — |
W2[1,0] | -0.7 | — | — | — | — |
b2[0] | 0.05 | — | — | — | — |
from mlp_numpy import gradients, loss
G = gradients(P, X, Y)
h = 0.001
P[0][0, 0] += h; plus = loss(P, X, Y)
P[0][0, 0] -= 2*h; minus = loss(P, X, Y)
P[0][0, 0] += h
print(G[0][0, 0], (plus - minus) / (2*h))
The check uses H = 2, where the network has exactly nine scalar parameters; the same formulas apply unchanged to H = 12 and its 49 parameters.
Do not divide by B twice. The adjoint
G_Ŷ = 2(Ŷ − Y)/B already contains the batch average. Every downstream
gradient inherits it. This lesson uses analytic gradients for the update and
central finite differences to check their implementation.
What changes during one training step?
One Complete Training Step
| Parameter | Before | Gradient | After |
|---|---|---|---|
W1[0,0] | 0.7 | cleared | — |
W1[0,1] | -0.4 | cleared | — |
W1[1,0] | 0.3 | cleared | — |
W1[1,1] | 0.8 | cleared | — |
b1[0] | 0.1 | cleared | — |
b1[1] | -0.2 | cleared | — |
W2[0,0] | 0.9 | cleared | — |
W2[1,0] | -0.7 | cleared | — |
b2[0] | 0.05 | cleared | — |
import numpy as np
eta = 0.15
G = gradients(P, X, Y)
P_new = [p - eta*g for p, g in zip(P, G)]
print(loss(P, X, Y), loss(P_new, X, Y))
Trace one update. The forward pass reads the current parameters,
backward computes their gradients, and the optimizer uses those gradients to update
the parameters. For independent updates per batch, the training loop calls
optimizer.zero_grad() before backward so earlier gradients do not carry over.
A training loop begins with data
The synthetic one-step dynamics used throughout this lesson are
Sampling is noiseless: states are uniform in [−2, 2], controls in
[−1, 1], and each split uses an independent fixed seed.
| Split | Samples | Seed | Role |
|---|---|---|---|
| Train | 96 | 123 | Only these samples drive parameter updates |
| Validation | 32 | 456 | Model selection and convergence checks |
| Test | 32 | 789 | Used once after settings are frozen |
Dataset & Mini-batch Player
from torch.utils.data import TensorDataset, DataLoader
ds = TensorDataset(torch.tensor(Xtr), torch.tensor(Ytr))
loader = DataLoader(ds, batch_size=16, sampler=permutation(96, 1).tolist())
for X, Y in loader:
print(X.shape, Y.shape) # shuffle only the training set
A Dataset stores samples; a DataLoader owns the iteration order and groups samples into batches. In PyTorch the sampler is the part you control when you need to reproduce the exact NumPy shuffle.
Epoch ≠ iteration. An epoch is one full traversal of the training set; an iteration is one parameter update on one mini-batch. With 96 samples and batch size 16 there are six iterations per epoch, and the last batch may be shorter when the batch size does not divide 96. Exclude validation and test samples from training batches, and real trajectory data should be split by complete trajectory to avoid adjacent-window leakage.
Train an MLP and inspect convergence
Live MLP Training Laboratory
from mlp_numpy import train
P, history = train(H=12, kind='tanh', lr=0.050, bs=16, epochs=0)
print(history[-1])
Read the curve correctly. Each point recomputes MSE over the whole training and validation sets after an epoch — not on the last mini-batch. The plot uses a base-10 logarithmic loss axis so that late-stage improvements stay visible. A rising validation curve while training loss falls can indicate overfitting. Compare the trend over several epochs. If loss grows sharply from the start, check the learning rate.
Parameter count
For 2 → H → 1 with biases: 2H + H + H + 1 = 4H + 1. With H = 12 that is 49 scalars.
Reproducibility
Initialization uses a fixed seed and the shuffle order depends only on the epoch number, so the same settings replay the same run.
What this lab omits
No momentum, weight decay, learning-rate schedule or early stopping. The browser lab uses hand-written matrix gradients and plain SGD, with no Autograd. Chapter 02 adds these engineering pieces.
One-step error is not rollout error
Start two evaluations with the same measured state , control sequence and trained model. They must produce the same first prediction, . The first chance for their predictions to differ is the second step. The only change is which state goes into the model.
| Evaluation | State supplied at time 1 | Prediction for time 2 |
|---|---|---|
| One-step along the observed trajectory | Read the measurement | |
| Recursive rollout | Feed back the model output |
Imagine pausing at time 1 and holding fixed. The gap is a horizontal displacement on the model's input–output curve. Read the curve at those two inputs. The vertical gap is the extra change in the second prediction caused by feedback.
A shallow response shrinks the gap. On a segment with slope ½, moving the input by one unit moves the output by half a unit.

A steep response amplifies the gap. On a segment with slope 2, the same input displacement moves the output by two units.

These two illustrative model curves use the same axis scales. The total rollout error also includes the model's error at the measured state. Add and subtract its prediction there to separate the two effects:
Here is the true dynamics. The two signed terms can reinforce or cancel each other. In the trained-model plot below, switch the input source at step 2 to compare these predictions on the same trajectory.
Nonlinear Dynamics Rollout
Change the initial state, control or horizon
import numpy as np
from mlp_numpy import forward, target
P = [np.load('mlp_numpy.npz')[k] for k in ('W1', 'b1', 'W2', 'b2')]
a = b = 1.8
u = -0.3
for k in range(2):
b = forward(P, np.array([[b, u]]))[2][0, 0]
a = target(np.array([[a, u]]))[0, 0]
print(k + 1, a, b)
Compare on the same trajectory. The recursive and true-state-input RMSE values use the same starting state, controls, and time horizon. Their difference shows how feedback changed error on this trajectory. The separate one-step test RMSE summarizes a different set of state–input pairs.
Learn by coding — NumPy and PyTorch
01 — Forward pass and loss in NumPy
Predict every shape before revealing the output. The target values are held fixed for this three-sample toy batch.
import numpy as np
X = np.array([[1.0, 0.5], [-0.5, 1.0], [0.2, -0.8]])
Y = np.array([[1.1], [-0.2], [0.4]])
W1 = np.array([[0.7, -0.4], [0.3, 0.8]])
b1 = np.array([0.1, -0.2])
W2 = np.array([[0.9], [-0.7]])
b2 = np.array([0.05])
Z = X @ W1 + b1
A = np.tanh(Z)
Yhat = A @ W2 + b2
L = np.mean((Yhat - Y) ** 2)
print(Z.shape, A.shape, Yhat.shape, round(L, 8))
Z and A keep the batch and hidden axes. The output layer contracts H to 1. np.mean reduces the squared residuals to one scalar.
02 — Manual gradients and a central-difference check
The adjoint already includes the 2/B factor. The finite-difference function perturbs one scalar at a time and restores it.
import numpy as np
def forward(P, X):
W1, b1, W2, b2 = P
Z = X @ W1 + b1
A = np.tanh(Z)
return Z, A, A @ W2 + b2
def loss(P, X, Y):
return np.mean((forward(P, X)[2] - Y) ** 2)
def gradients(P, X, Y):
W1, b1, W2, b2 = P
Z, A, Yhat = forward(P, X)
G = 2 * (Yhat - Y) / Y.size
dW2, db2 = A.T @ G, G.sum(axis=0)
dZ = (G @ W2.T) * (1 - A * A)
return [X.T @ dZ, dZ.sum(axis=0), dW2, db2]
def central(P, X, Y, layer, idx, h=1e-3):
plus = [q.copy() for q in P]
minus = [q.copy() for q in P]
plus[layer][idx] += h
minus[layer][idx] -= h
return (loss(plus, X, Y) - loss(minus, X, Y)) / (2 * h)
P = [np.array([[0.7, -0.4], [0.3, 0.8]]), np.array([0.1, -0.2]),
np.array([[0.9], [-0.7]]), np.array([0.05])]
X = np.array([[1.0, 0.5], [-0.5, 1.0], [0.2, -0.8]])
Y = np.array([[1.1], [-0.2], [0.4]])
G = gradients(P, X, Y)
print('analytic W1[0,0]', round(G[0][0, 0], 8))
print('central W1[0,0]', round(central(P, X, Y, 0, (0, 0)), 8))
They agree to about seven significant digits at h = 1e-3. Reducing h further eventually increases the error because of floating-point cancellation.
03 — Complete NumPy training loop
The custom RNG matches the browser lab exactly: seeds 123, 456 and 789 generate the splits, seed 42 initializes the weights, and epoch e shuffles with seed 1000 + e.
import numpy as np
class RNG:
def __init__(self, seed): self.state = seed
def uniform(self):
self.state = (1664525 * self.state + 1013904223) % 2**32
return self.state / 2**32
def sample(self, lo, hi): return lo + (hi - lo) * self.uniform()
def target(X):
x, u = X[:, :1], X[:, 1:2]
return 0.65 * x + 0.5 * np.sin(2 * x) + 0.35 * u
def make_data(n, seed):
r = RNG(seed)
X = np.array([[r.sample(-2, 2), r.sample(-1, 1)] for _ in range(n)])
return X, target(X)
def initialize(H=12):
r = RNG(42)
return [np.array([[r.sample(-1, 1) / np.sqrt(2) for _ in range(H)] for _ in range(2)]),
np.zeros(H),
np.array([[r.sample(-1, 1) / np.sqrt(H)] for _ in range(H)]),
np.zeros(1)]
def activation(Z, kind='tanh'):
if kind == 'tanh': return np.tanh(Z)
if kind == 'relu': return np.maximum(Z, 0)
return Z
def forward(P, X, kind='tanh'):
W1, b1, W2, b2 = P
Z = X @ W1 + b1
A = activation(Z, kind)
return Z, A, A @ W2 + b2
def loss(P, X, Y, kind='tanh'):
return np.mean((forward(P, X, kind)[2] - Y) ** 2)
def gradients(P, X, Y, kind='tanh'):
W1, b1, W2, b2 = P
Z, A, Yhat = forward(P, X, kind)
G = 2 * (Yhat - Y) / Y.size
dW2, db2 = A.T @ G, G.sum(axis=0)
local = 1 - A * A if kind == 'tanh' else (Z > 0).astype(float)
dZ = (G @ W2.T) * local
return [X.T @ dZ, dZ.sum(axis=0), dW2, db2]
def permutation(n, epoch):
r, ids = RNG(1000 + epoch), list(range(n))
for i in range(n - 1, 0, -1):
j = int(r.uniform() * (i + 1))
ids[i], ids[j] = ids[j], ids[i]
return np.array(ids)
Xtr, Ytr = make_data(96, 123)
Xva, Yva = make_data(32, 456)
Xte, Yte = make_data(32, 789)
P = initialize(12)
history = [(loss(P, Xtr, Ytr), loss(P, Xva, Yva))]
for epoch in range(1, 161):
order = permutation(len(Xtr), epoch)
for k in range(0, len(order), 16):
ids = order[k:k + 16]
G = gradients(P, Xtr[ids], Ytr[ids])
P = [p - 0.05 * g for p, g in zip(P, G)]
history.append((loss(P, Xtr, Ytr), loss(P, Xva, Yva)))
print('initial train MSE:', round(history[0][0], 6))
print('final train MSE: ', round(history[-1][0], 6))
print('validation MSE: ', round(history[-1][1], 6))
print('held-out test MSE:', round(loss(P, Xte, Yte), 6))
np.savez('mlp_numpy.npz', W1=P[0], b1=P[1], W2=P[2], b2=P[3])
Validation and test data never appear in gradients; they only measure generalization. Test is evaluated once, after every setting is fixed.
04 — Check manual gradients against Autograd
PyTorch stores weight as (out, in), so the manual (in, out) matrices are transposed when copied and compared.
import numpy as np
import torch
from torch import nn
from mlp_numpy import initialize, gradients, Xtr, Ytr
torch.manual_seed(42)
def tensor(x): return torch.as_tensor(x, dtype=torch.float64)
class MLP(nn.Module):
def __init__(self, H=12):
super().__init__()
self.fc1 = nn.Linear(2, H, dtype=torch.float64)
self.fc2 = nn.Linear(H, 1, dtype=torch.float64)
def forward(self, x):
return self.fc2(torch.tanh(self.fc1(x)))
P0 = initialize()
model = MLP(len(P0[1]))
with torch.no_grad():
model.fc1.weight.copy_(tensor(P0[0].T))
model.fc1.bias.copy_(tensor(P0[1]))
model.fc2.weight.copy_(tensor(P0[2].T))
model.fc2.bias.copy_(tensor(P0[3]))
X, Y = tensor(Xtr[:16]), tensor(Ytr[:16])
criterion = nn.MSELoss()
criterion(model(X), Y).backward()
manual = gradients(P0, Xtr[:16], Ytr[:16])
reference = [model.fc1.weight.grad.T, model.fc1.bias.grad,
model.fc2.weight.grad.T, model.fc2.bias.grad]
for a, b in zip(manual, reference):
np.testing.assert_allclose(a, b.detach().numpy(), atol=1e-12, rtol=1e-10)
print('Manual gradients match Autograd')
Without the transpose the weight matrix is interpreted in the wrong orientation, the forward values differ, and the gradient comparison fails.
05 — Same experiment with Autograd, optimizer and checkpoint
An explicit sampler reproduces the NumPy shuffle order. Save both the hidden width and the state_dict; only load checkpoints you trust.
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from mlp_numpy import Xtr, Ytr, Xva, Yva, permutation, initialize
torch.manual_seed(42)
def tensor(x): return torch.as_tensor(x, dtype=torch.float64)
class MLP(nn.Module):
def __init__(self, H=12):
super().__init__()
self.fc1 = nn.Linear(2, H, dtype=torch.float64)
self.fc2 = nn.Linear(H, 1, dtype=torch.float64)
def forward(self, x):
return self.fc2(torch.tanh(self.fc1(x)))
P0 = initialize(12)
model = MLP(12)
with torch.no_grad():
model.fc1.weight.copy_(tensor(P0[0].T))
model.fc1.bias.copy_(tensor(P0[1]))
model.fc2.weight.copy_(tensor(P0[2].T))
model.fc2.bias.copy_(tensor(P0[3]))
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.05)
trainset = TensorDataset(tensor(Xtr), tensor(Ytr))
for epoch in range(1, 161):
model.train()
loader = DataLoader(trainset, batch_size=16,
sampler=permutation(96, epoch).tolist())
for xb, yb in loader:
optimizer.zero_grad(set_to_none=True)
loss = criterion(model(xb), yb)
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
val = criterion(model(tensor(Xva)), tensor(Yva)).item()
if epoch % 40 == 0:
print(epoch, 'validation MSE', round(val, 6))
torch.save({'hidden': 12, 'model_state': model.state_dict()}, 'mlp.pt')
ckpt = torch.load('mlp.pt', map_location='cpu', weights_only=True)
restored = MLP(ckpt['hidden'])
restored.load_state_dict(ckpt['model_state'])
restored.eval()
print('checkpoint reloaded')
The class and the hidden width must match before load_state_dict. To resume training, also save the optimizer state, the epoch and the RNG state.
06 — Rollout evaluation
Fit a linear least-squares baseline on the same training data, then feed both models back recursively.
import numpy as np
from mlp_numpy import forward, target, Xtr, Ytr
P = [np.load('mlp_numpy.npz')[k] for k in ('W1', 'b1', 'W2', 'b2')]
coef = np.linalg.lstsq(np.c_[Xtr, np.ones(len(Xtr))], Ytr, rcond=None)[0]
truth = lambda x, u: target(np.array([[x, u]]))[0, 0]
mlp = lambda x, u: forward(P, np.array([[x, u]]))[2][0, 0]
linear = lambda x, u: float((np.array([x, u, 1.0]) @ coef).item())
def rollout(fn, x0, u, horizon):
xs = [x0]
for _ in range(horizon):
xs.append(fn(xs[-1], u))
return np.array(xs)
actual = rollout(truth, 1.8, -0.3, 20)
for name, fn in [('MLP', mlp), ('Linear', linear)]:
pred = rollout(fn, 1.8, -0.3, 20)
print(name, 'rollout RMSE:', round(np.sqrt(np.mean((pred[1:] - actual[1:]) ** 2)), 6))
The MLP has small one-step error but still drifts to a slightly wrong fixed point. The linear model extrapolates poorly outside the sampled band.
Mini project — train, validate, checkpoint
Goal: without looking at the lab answer, train three hidden widths (4, 12, 24) on the same split and produce one table with final train MSE, validation MSE and rollout RMSE. Then write two sentences explaining which width you would choose and why validation, not test, drove the decision.
import numpy as np
from mlp_numpy import make_data, initialize, gradients, permutation, forward
# TODO: loop over H in (4, 12, 24), re-initializing with the same seed
# TODO: train 160 epochs with batch size 16 and learning rate 0.05
# TODO: record full-set train and validation MSE after the last epoch
# TODO: run a 20-step rollout from x0=1.8 with u=-0.3 and report RMSE
# TODO: keep the test split untouched until the width is chosen
Change one factor at a time. Record the exact seed and batch order with every result.