2.3 Linear Regression Implementation from Scratch
Now that we have the theory of linear regression (Section 2.1) and a synthetic dataset with known ground-truth parameters (Section 2.2), we are ready to put both into code. In this section, we build every component of the training pipeline from scratch—parameter initialization, the linear forward pass, the squared loss, automatic differentiation, the minibatch iterator, and the SGD update loop—relying only on basic tensor arithmetic and automatic differentiation. Writing each step by hand strips away hidden machinery so we can see how gradients flow and how hyperparameters such as the learning rate shape convergence. Once every moving part is clear, Section 2.4 organizes these components into reusable classes (Module, DataModule, and Trainer), and Section 2.5 re-expresses the same model in a handful of lines using framework layers, built-in loss functions, and optimizers.
2.3.1 Model, Loss, and Gradient#
Let us start by generating synthetic examples ( for training and for validation) with true parameters , , and noise :
w_star, b_star, noise = d2l.tensor([2, -3.4]), 4.2, 0.01
X, y = d2l.synthetic_data(w_star, b_star, noise, 2000)
X_train, y_train, X_val, y_val = X[:1000], y[:1000], X[1000:], y[1000:]2.3.1.1 The Parameters#
Our model has a weight vector and a scalar bias . We initialize the weights with small random draws from and set the bias to (for linear regression, starting from all zeros works just as well—see Exercise 1—though breaking symmetries with random weights becomes essential once we stack hidden layers in Chapter 4).
We set requires_grad=True on both tensors so PyTorch's autograd engine records every operation involving them.
def init_params(sigma=0.01):
w = torch.normal(0, sigma, (2, 1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
return w, b2.3.1.2 The Forward Pass#
Given a minibatch design matrix , parameters , and scalar bias , the linear prediction is a single matrix-vector product plus a broadcasted addition:
def linreg(X, w, b):
"""The linear regression model."""
return d2l.matmul(X, w) + b
2.3.1.3 The Loss#
Next we implement the mean squared error . We reshape y into a column vector (-1, 1) to match y_hat: if one tensor had shape (n, 1) and the other (n,), subtracting them would silently broadcast into an (n, n) matrix of all pairwise differences. What makes this bug treacherous is that training does not fail. The mean over all squared differences is smallest when every prediction equals the average label, so SGD drives to and to , and the loss falls smoothly to half the variance of the labels, for our data. A falling loss curve is therefore weak evidence that the code is right. Later in this section we check the loss against the value it should reach, and the parameters against the truth.
def squared_loss(y_hat, y):
"""Half the squared error, averaged over the minibatch."""
return d2l.reduce_mean((y_hat - d2l.reshape(y, (-1, 1))) ** 2 / 2)
2.3.1.4 The Gradient#
Before letting automatic differentiation take over, let us check on a single minibatch of 32 examples that automatic differentiation produces the same gradients as our hand-derived formulas from Section 2.1.2.3:
Let us slice out the first 32 training examples (Xb, yb) and compare the analytical gradients with automatic differentiation:
Xb, yb = X_train[:32], y_train[:32]
w, b = init_params()
squared_loss(linreg(Xb, w, b), yb).backward()
with torch.no_grad():
r = linreg(Xb, w, b) - yb # One error per example
by_hand = torch.cat([Xb.T @ r, r.sum(0, keepdim=True)]) / len(yb)
by_autograd = torch.cat([w.grad, b.grad[None]])
print('gradient:', d2l.numpy(by_autograd).reshape(-1).round(4))
print(f'largest difference: {float(abs(by_hand - by_autograd).max()):.1g}')gradient: [-4.9511 7.7252 -4.6794]
largest difference: 0
The largest entrywise discrepancy is zero (or at most , float32
rounding precision), confirming that autograd computes the minibatch
gradient we expect. From here on, we let the framework differentiate our forward pass and loss automatically.
2.3.2 Training from Scratch#
2.3.2.1 The Update#
At each step, we update the parameters in the direction opposite their gradients, , taking care not to record the parameter update itself inside the computational graph.
2.3.2.2 Minibatches#
To sweep through the dataset in random minibatches of size , our generator minibatches draws a fresh random permutation of the indices at the start of each epoch and yields successive slices of size batch_size (Exercise 2):
def minibatches(X, y, batch_size):
"""Minibatches of (X, y), in a new random order on every call."""
indices = np.random.permutation(len(X))
for i in range(0, len(indices), batch_size):
batch = indices[i : i + batch_size]
yield X[batch], y[batch]With training examples and batch_size=32, one epoch yields
minibatches: full batches of examples
plus one remainder batch of . Let us inspect one pass over the generator and
see what happens if we accidentally iterate over the same generator a second
time.
loader = minibatches(X_train, y_train, 32)
sizes = [len(y) for X, y in loader]
print(f'{len(sizes)} minibatches, the last of size {sizes[-1]}')
print(f'second pass: {len([y for X, y in loader])} minibatches')
32 minibatches, the last of size 8
second pass: 0 minibatches
Each yielded pair (Xb, yb) has shapes (32, 2) and (32, 1). The first pass (one epoch) yields all minibatches as expected, while the second pass
yields zero. A Python generator is single-use and exhausts silently once
consumed, which is why our training loop calls minibatches(...) fresh at the
start of every epoch.
2.3.2.3 The Training Loop#
We now assemble the complete training loop in train(lr, num_epochs, batch_size). In each epoch, we iterate over minibatches(X, y, batch_size), compute the minibatch loss, differentiate it with respect to w and b, and apply the SGD step:
def train(lr, num_epochs=10, batch_size=32):
w, b = init_params()
val_losses = []
for epoch in range(num_epochs):
for Xb, yb in minibatches(X_train, y_train, batch_size):
loss = squared_loss(linreg(Xb, w, b), yb) # forward pass, loss
loss.backward() # backward pass
with torch.no_grad(): # not recorded:
for param in (w, b):
param -= lr * param.grad # update
param.grad.zero_() # clear
with torch.no_grad():
val_losses.append(squared_loss(linreg(X_val, w, b), y_val).item())
return w, b, val_lossesThe loop ends by clearing each gradient, because PyTorch adds a new gradient to the stored one instead of replacing it (Section 1.5).
Notice that the core training loop is only a dozen lines of code, and those same four steps (forward pass loss backward pass parameter update, drawn in Figure 2.3.1) train every deep network in the rest of this book.
One step of minibatch SGD. The forward pass computes the predictions for a minibatch, the loss reduces them to a single number, the backward pass differentiates that number with respect to the parameters, and the update moves the parameters against the gradient. The cycle then repeats with the next minibatch.
2.3.3 Checking the Implementation#
2.3.3.1 The Expected Loss#
How small should the loss become when training succeeds? Even at the true parameters , the residuals equal the Gaussian noise , so the expected loss is the irreducible noise floor:
At initialization (), by contrast, the residual is , which has mean and variance . Thus the expected initial loss is
Over the course of training, we therefore expect the loss to plunge by five orders of magnitude, from roughly down to the noise floor .
The same computation also predicts how fast the loss should fall. At arbitrary parameters, the residual is . Because the two features are independent standard normal variables and the noise is independent of both, every cross term has expectation zero, and
The gradient of this expected loss with respect to is simply the parameter error , so a gradient step of size shrinks the parameter error by the factor and the excess loss above the floor by . Minibatch gradients match the expected gradient only on average, so this gives an approximate trajectory rather than an exact identity. At , one epoch of minibatch updates should reduce the excess loss by a factor of roughly .
2.3.3.2 The Training Run#
Let us run train for 10 epochs with learning rate and minibatch size , plotting the validation loss after each epoch on a logarithmic scale:
w, b, val_losses = train(lr=0.03)
d2l.plot(list(range(1, 11)), val_losses, xlabel='epoch',
ylabel='validation loss', yscale='log')Sure enough, the validation loss plunges along a straight line, dropping roughly per epoch before flattening out near the predicted floor of around epoch 7 or 8. Let us compare the measured excess loss against our closed-form prediction epoch by epoch over the first seven epochs.
floor = noise ** 2 / 2 # sigma^2 / 2
excess = (float(d2l.reduce_sum(w_star ** 2)) + b_star ** 2) / 2 # 16.6
for epoch, loss in enumerate(val_losses[:7], start=1):
excess *= (1 - 0.03) ** (2 * 32) # 32 steps per epoch
print(f'epoch {epoch}: measured {loss - floor:.1e}, '
f'predicted {excess:.1e}')epoch 1: measured 2.1e+00, predicted 2.4e+00
epoch 2: measured 2.8e-01, predicted 3.4e-01
epoch 3: measured 3.6e-02, predicted 4.8e-02
epoch 4: measured 4.8e-03, predicted 6.8e-03
epoch 5: measured 6.5e-04, predicted 9.7e-04
epoch 6: measured 9.1e-05, predicted 1.4e-04
epoch 7: measured 1.2e-05, predicted 2.0e-05
Measured and predicted excess losses track each other tightly over the early epochs and gradually drift apart, by at most a modest factor of 3 or 4 by epoch 7. Why the slight drift? Our idealized prediction assumed the sample covariance matrix (see exercise 1) equals the exact identity matrix. On a finite sample of examples, its eigenvalues sit within roughly of , and over several epochs these small deviations compound, so the empirical run drifts slightly ahead of or behind the idealized prediction. Both the decay rate and the noise floor match theory.
2.3.3.3 Recovered Parameters#
Because our dataset is synthetic, we can also compare the learned directly against the true and :
w_error = d2l.numpy(d2l.reshape(w, w_star.shape) - w_star)
b_error = d2l.numpy(b - b_star)
print('error in w:', ', '.join(f'{e:.1e}' for e in w_error))
print('error in b:', ', '.join(f'{e:.1e}' for e in b_error))error in w: 1.7e-04, 5.1e-04
error in b: -4.6e-04
Both the weights and the bias are recovered to within a thousandth, matching the statistical estimation floor we found with the least-squares solver in Section 2.2.
2.3.3.4 The Learning Rate#
What happens if we choose the learning rate poorly? Let us run the exact same 10-epoch loop across four learning rates spanning three orders of magnitude, , and print the final validation loss of each run (Exercise 1):
for lr in [0.003, 0.03, 0.3, 3]:
val_loss = train(lr)[2][-1]
print(f'lr = {lr:<6} validation loss: {val_loss:.1e}')lr = 0.003 validation loss: 2.1e+00
lr = 0.03 validation loss: 5.0e-05
lr = 0.3 validation loss: 5.1e-05
lr = 3 validation loss: nan
The results match our theory across the board. At , the error
contracts by only per step, leaving the loss around to after ten
epochs (right near ). At , the
model rockets down to the noise floor within the very first epoch. And at
, every update roughly doubles the error with alternating sign, quickly
overflowing to nan. Keep in mind that the stability ceiling of is a property
of our data scaling, not a universal constant of SGD: it arises because our
features have unit variance. Scaling a feature by increases the loss
curvature along that weight by and shrinks the maximum stable learning rate
to roughly —a major practical reason why we standardize input features
before training (Section 1.2).
Next, Section 2.4 packages the training
machinery we just built into reusable object-oriented classes (Module,
DataModule, and Trainer), and Section 2.5 shows how to swap
our hand-written tensors, loss, and updater for ready-made framework components.
2.3.4 Summary#
A complete training loop requires only four primitives: a parameterized forward pass , a scalar loss , reverse-mode automatic differentiation, and a minibatch SGD update run outside gradient recording. Because a falling loss curve alone does not prove that code is bug-free (a silent shape mismatch can still lower loss toward half the label variance), we verify our implementation quantitatively on synthetic data: the validation loss decays exponentially at the predicted rate per epoch to the noise floor , and the learned parameters match within . Across learning rates, small step sizes crawl slowly, moderate step sizes reach the noise floor quickly, and step sizes exceeding overshoot the quadratic bowl and diverge.
2.3.5 Exercises#
- [code] Initialization at the extremes.
init_paramsdraws the weights with standard deviationsigma=0.01. Predict whether training reaches the noise floor when the weights are initialized to exactly zero, and whensigma=1000. Use (2.3.4) to estimate how many more epochs the second case needs at learning rate 0.03, then check your estimate.
- [code] Second derivatives. Compute by hand the Hessian of the
minibatch loss with respect to , and state which
quantities it depends on. Then compute it with automatic differentiation via
torch.func.hessian(Section 1.5) for one fixed minibatch of the synthetic data, once at initialization and once after training. Compare both results with your formula and with the curvature of (2.3.4).
-
[code] Stability and minibatch size. ● The expected loss predicts that steps along its gradient diverge for . Let be an input with a appended for the bias.
- For full-batch gradient descent, show that each step multiplies the difference between the parameters and the least-squares solution by the matrix , where is the average of over the training set. Compute the eigenvalues of and predict the largest stable learning rate.
- Train with minibatches of 1,000, 32, and 1 example, giving each run the same number of updates, say 320. For each minibatch size, find the largest learning rate in a grid of your choice at which the final training loss is below .
- Show that a step on a single example multiplies the component of the parameter error along by , and use to explain the limit you found for minibatches of one example.
-
Why reshuffle.
minibatchesdraws a fresh random order in every epoch. Explain which property of the minibatch gradient this preserves. Then construct a fixed ordering of the training set, such as sorting by label, under which minibatch SGD without reshuffling behaves differently, and describe the trajectory of within an epoch and across epochs. -
[code] Robust losses. ● Replace
squared_losswith the mean absolute errord2l.reduce_mean(d2l.abs(y_hat - d2l.reshape(y, (-1, 1)))).- Train on the synthetic data and compare the recovered parameters and the loss curve with those of the squared loss.
- Set one training label to , the corruption used in Section 2.1.1.3, and train with both losses. Record after every minibatch update, plot it against the iteration for both runs, and explain the pattern of the squared-loss curve, including what determines its final value.
- On the corrupted data, replace the loss with the minibatch average of the Huber loss
whose quadratic part matches the squared loss of this section. Train for , and plot the distance of the learned bias from the generating bias against on logarithmic axes. Explain the shape of the curve from the derivative of with respect to , and relate the result to the penalty curves of Figure 2.1.6.