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 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 \(2{,}000\) synthetic examples (\(1{,}000\) for training and \(1{,}000\) for validation) with true parameters \(\mathbf{w}^* = (2, -3.4)^\top\), \(b^* = 4.2\), and noise \(\sigma = 0.01\):
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:]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, d2l.get_key())
X_train, y_train, X_val, y_val = X[:1000], y[:1000], X[1000:], y[1000:]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 \(\mathbf{w} \in \mathbb{R}^2\) and a scalar bias \(b \in \mathbb{R}\). We initialize the weights with small random draws from \(\mathcal{N}(0, 0.01^2)\) and set the bias to \(0\) (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.
We wrap both tensors in tf.Variable, which TensorFlow’s GradientTape watches automatically.
JAX arrays are immutable values; jax.grad differentiates pure functions with respect to their arguments directly without mutating flags on the arrays.
We call attach_grad() on both parameters to allocate gradient buffers and instruct MXNet to track operations inside autograd.record().
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, bdef init_params(sigma=0.01):
w = tf.Variable(tf.random.normal((2, 1), stddev=sigma))
b = tf.Variable(tf.zeros(1))
return w, bdef init_params(sigma=0.01):
return jax.random.normal(d2l.get_key(), (2, 1)) * sigma, jnp.zeros(1)def init_params(sigma=0.01):
w, b = mnp.random.normal(0, sigma, (2, 1)), mnp.zeros(1)
w.attach_grad()
b.attach_grad()
return w, b2.3.1.2 The Forward Pass
Given a minibatch design matrix \(\mathbf{X} \in \mathbb{R}^{|\mathcal{B}| \times d}\), parameters \(\mathbf{w} \in \mathbb{R}^{d \times 1}\), and scalar bias \(b\), the linear prediction \(\hat{\mathbf{y}} = \mathbf{X}\mathbf{w} + b\) is a single matrix-vector product plus a broadcasted addition:
def linreg(X, w, b):
"""The linear regression model."""
return d2l.matmul(X, w) + b2.3.1.3 The Loss
Next we implement the mean squared error \(L(\mathbf{w}, b) = \frac{1}{2|\mathcal{B}|}\sum_{i \in \mathcal{B}} (\hat{y}^{(i)} - y^{(i)})^2\). 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 \(n^2\) squared differences is smallest when every prediction equals the average label, so SGD drives \(\mathbf{w}\) to \(\mathbf{0}\) and \(b\) to \(\bar{y}\), and the loss falls smoothly to half the variance of the labels, \(\frac{1}{2}(2^2 + 3.4^2) \approx 7.8\) 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:
\[\frac{\partial L}{\partial \mathbf{w}} = \frac{1}{|\mathcal{B}|} \mathbf{X}^\top (\hat{\mathbf{y}} - \mathbf{y}), \qquad \frac{\partial L}{\partial b} = \frac{1}{|\mathcal{B}|} \sum_{i \in \mathcal{B}} (\hat{y}^{(i)} - y^{(i)}). \tag{2.3.1}\]
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
with tf.GradientTape() as tape:
loss = squared_loss(linreg(Xb, w, b), yb)
grad_w, grad_b = tape.gradient(loss, [w, b])
r = linreg(Xb, w, b) - yb # One error per example
by_hand = tf.concat([tf.transpose(Xb) @ r,
tf.reduce_sum(r, 0, keepdims=True)], 0) / len(yb)
by_autograd = tf.concat([grad_w, grad_b[None]], 0)
difference = tf.reduce_max(abs(by_hand - by_autograd))
print('gradient:', d2l.numpy(by_autograd).reshape(-1).round(4))
print(f'largest difference: {float(difference):.1g}')gradient: [-1.6582 2.3576 -5.0225]
largest difference: 1e-07
loss_wb = lambda w, b: squared_loss(linreg(Xb, w, b), yb)
grad_w, grad_b = jax.grad(loss_wb, argnums=(0, 1))(w, b)
r = linreg(Xb, w, b) - yb # One error per example
by_hand = jnp.concatenate([Xb.T @ r, r.sum(0, keepdims=True)]) / len(yb)
by_autograd = jnp.concatenate([grad_w, grad_b[None]])
print('gradient:', d2l.numpy(by_autograd).reshape(-1).round(4))
print(f'largest difference: {float(abs(by_hand - by_autograd).max()):.1g}')gradient: [-1.2946 4.0718 -4.8165]
largest difference: 2e-07
with autograd.record():
loss = squared_loss(linreg(Xb, w, b), yb)
loss.backward()
r = linreg(Xb, w, b) - yb # One error per example
by_hand = mnp.concatenate([Xb.T @ r, r.sum(0, keepdims=True)]) / len(yb)
by_autograd = mnp.concatenate([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: [-2.6313 2.827 -3.9772]
largest difference: 0
The largest entrywise discrepancy is zero (or at most \(\sim 10^{-7}\), 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, \((\mathbf{w}, b) \leftarrow (\mathbf{w}, b) - \eta\,(\nabla_{\mathbf{w}} L, \nabla_b L)\), 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 \(|\mathcal{B}|\), our generator minibatches draws a fresh random permutation of the indices \(0, \ldots, n - 1\) 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]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 tf.gather(X, batch), tf.gather(y, batch)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]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 \(1{,}000\) training examples and batch_size=32, one epoch yields \(\lceil 1000 / 32 \rceil = 32\) minibatches: \(31\) full batches of \(32\) examples plus one remainder batch of \(8\). 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 \(32\) 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_lossesdef 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):
with tf.GradientTape() as tape: # forward pass, loss
loss = squared_loss(linreg(Xb, w, b), yb)
grads = tape.gradient(loss, [w, b]) # backward pass
for param, grad in zip((w, b), grads):
param.assign_sub(lr * grad) # update
val_losses.append(float(squared_loss(linreg(X_val, w, b), y_val)))
return w, b, val_losses@jax.jit
def sgd_step(w, b, X, y, lr):
loss_wb = lambda w, b: squared_loss(linreg(X, w, b), y) # forward, loss
grad_w, grad_b = jax.grad(loss_wb, argnums=(0, 1))(w, b) # backward
return w - lr * grad_w, b - lr * grad_b # update
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):
w, b = sgd_step(w, b, Xb, yb, lr)
val_losses.append(float(squared_loss(linreg(X_val, w, b), y_val)))
return w, b, val_lossesdef 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):
with autograd.record(): # forward pass, loss
loss = squared_loss(linreg(Xb, w, b), yb)
loss.backward() # backward pass
for param in (w, b):
param -= lr * param.grad # update
val_losses.append(float(squared_loss(linreg(X_val, w, b), y_val)))
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 \(\rightarrow\) loss \(\rightarrow\) backward pass \(\rightarrow\) parameter update, drawn in Figure 2.3.1) train every deep network in the rest of this book.
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 \((\mathbf{w}^*, b^*)\), the residuals equal the Gaussian noise \(\hat{y}^{(i)} - y^{(i)} = -\epsilon^{(i)} \sim \mathcal{N}(0, \sigma^2)\), so the expected loss is the irreducible noise floor:
\[\mathbb{E}\left[L(\mathbf{w}^*, b^*)\right] = \frac{1}{2}\,\mathbb{E}\left[\epsilon^2\right] = \frac{1}{2}\sigma^2 = \frac{1}{2}(0.01)^2 = 0.00005. \tag{2.3.2}\]
At initialization (\(\mathbf{w} \approx \mathbf{0}, b = 0\)), by contrast, the residual is \(-y = -(\mathbf{x}^\top\mathbf{w}^* + b^* + \epsilon)\), which has mean \(-b^* = -4.2\) and variance \(\|\mathbf{w}^*\|_2^2 + \sigma^2 = 2^2 + (-3.4)^2 + 0.01^2 = 15.5601\). Thus the expected initial loss is
\[\mathbb{E}\left[L(\mathbf{0}, 0)\right] = \frac{1}{2}\left((b^*)^2 + \|\mathbf{w}^*\|_2^2 + \sigma^2\right) = \frac{1}{2}(17.64 + 15.5601) \approx 16.6. \tag{2.3.3}\]
Over the course of training, we therefore expect the loss to plunge by five orders of magnitude, from roughly \(16.6\) down to the noise floor \(0.00005\).
The same computation also predicts how fast the loss should fall. At arbitrary parameters, the residual is \(r = \mathbf{x}^\top(\mathbf{w} - \mathbf{w}^*) + (b - b^*) - \epsilon\). Because the two features are independent standard normal variables and the noise is independent of both, every cross term has expectation zero, and
\[\mathbb{E}\left[L(\mathbf{w}, b)\right] = \tfrac{1}{2}\|\mathbf{w} - \mathbf{w}^*\|_2^2 + \tfrac{1}{2}(b - b^*)^2 + \tfrac{1}{2}\sigma^2. \tag{2.3.4}\]
The gradient of this expected loss with respect to \((\mathbf{w}, b)\) is simply the parameter error \((\mathbf{w} - \mathbf{w}^*, b - b^*)\), so a gradient step of size \(\eta\) shrinks the parameter error by the factor \(1 - \eta\) and the excess loss above the floor by \((1 - \eta)^2\). Minibatch gradients match the expected gradient only on average, so this gives an approximate trajectory rather than an exact identity. At \(\eta = 0.03\), one epoch of \(32\) minibatch updates should reduce the excess loss by a factor of roughly \(1 / (1 - 0.03)^{64} \approx 7\).
2.3.3.2 The Training Run
Let us run train for 10 epochs with learning rate \(\eta = 0.03\) and minibatch size \(|\mathcal{B}| = 32\), 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 \(7\times\) per epoch before flattening out near the predicted floor of \(5 \times 10^{-5}\) 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
epoch 1: measured 2.8e+00, predicted 2.4e+00
epoch 2: measured 4.6e-01, predicted 3.4e-01
epoch 3: measured 7.8e-02, predicted 4.8e-02
epoch 4: measured 1.3e-02, predicted 6.8e-03
epoch 5: measured 2.1e-03, predicted 9.7e-04
epoch 6: measured 3.6e-04, predicted 1.4e-04
epoch 7: measured 6.2e-05, predicted 2.0e-05
epoch 1: measured 2.6e+00, predicted 2.4e+00
epoch 2: measured 3.9e-01, predicted 3.4e-01
epoch 3: measured 5.9e-02, predicted 4.8e-02
epoch 4: measured 8.9e-03, predicted 6.8e-03
epoch 5: measured 1.3e-03, predicted 9.7e-04
epoch 6: measured 2.1e-04, predicted 1.4e-04
epoch 7: measured 3.1e-05, predicted 2.0e-05
epoch 1: measured 2.6e+00, predicted 2.4e+00
epoch 2: measured 3.9e-01, predicted 3.4e-01
epoch 3: measured 5.8e-02, predicted 4.8e-02
epoch 4: measured 8.7e-03, predicted 6.8e-03
epoch 5: measured 1.3e-03, predicted 9.7e-04
epoch 6: measured 2.0e-04, predicted 1.4e-04
epoch 7: measured 3.4e-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 \(\mathbf{H} = \frac{1}{n}\sum_i \tilde{\mathbf{x}}^{(i)}(\tilde{\mathbf{x}}^{(i)})^\top\) (see exercise 1) equals the exact identity matrix. On a finite sample of \(1{,}000\) examples, its eigenvalues sit within roughly \(10\%\) of \(1\), 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 \((\mathbf{w}, b)\) directly against the true \(\mathbf{w}^* = (2, -3.4)^\top\) and \(b^* = 4.2\):
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
error in w: -3.6e-04, 4.1e-04
error in b: 1.1e-05
error in w: -1.9e-04, 6.9e-04
error in b: -7.1e-04
error in w: 4.6e-04, 4.9e-04
error in b: -4.9e-04
Both the weights and the bias are recovered to within a thousandth, matching the statistical estimation floor \(\sigma / \sqrt{n} \approx 3 \times 10^{-4}\) 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, \(\eta \in \{0.003, 0.03, 0.3, 3\}\), 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
lr = 0.003 validation loss: 2.9e+00
lr = 0.03 validation loss: 5.2e-05
lr = 0.3 validation loss: 5.2e-05
lr = 3 validation loss: nan
lr = 0.003 validation loss: 2.7e+00
lr = 0.03 validation loss: 4.8e-05
lr = 0.3 validation loss: 5.7e-05
lr = 3 validation loss: nan
lr = 0.003 validation loss: 2.7e+00
lr = 0.03 validation loss: 5.2e-05
lr = 0.3 validation loss: 5.4e-05
lr = 3 validation loss: nan
The results match our theory across the board. At \(\eta = 0.003\), the error contracts by only \(0.997\) per step, leaving the loss around \(2\) to \(3\) after ten epochs (right near \(16.6 \times 0.997^{640} \approx 2.4\)). At \(\eta = 0.3\), the model rockets down to the noise floor within the very first epoch. And at \(\eta = 3\), every update roughly doubles the error with alternating sign, quickly overflowing to nan. Keep in mind that the stability ceiling of \(2\) 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 \(s > 1\) increases the loss curvature along that weight by \(s^2\) and shrinks the maximum stable learning rate to roughly \(2 / s^2\)—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 \(\hat{\mathbf{y}} = \mathbf{X}\mathbf{w} + b\), a scalar loss \(\frac{1}{2|\mathcal{B}|}\|\hat{\mathbf{y}} - \mathbf{y}\|_2^2\), 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 \((1 - \eta)^{64}\) per epoch to the noise floor \(\frac{1}{2}\sigma^2 = 5 \times 10^{-5}\), and the learned parameters match \((\mathbf{w}^*, b^*)\) within \(O(\sigma/\sqrt{n})\). Across learning rates, small step sizes crawl slowly, moderate step sizes reach the noise floor quickly, and step sizes exceeding \(2/\mu_{\max}\) 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 Equation 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 \(3 \times 3\) Hessian of the minibatch loss with respect to \(\boldsymbol{\theta} = (\mathbf{w}, b)\), 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 Equation 2.3.4.
[code] Stability and minibatch size. ● The expected loss predicts that steps along its gradient diverge for \(\eta > 2\). Let \(\tilde{\mathbf{x}} = (\mathbf{x}, 1)\) be an input with a \(1\) 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 \(\mathbf{I} - \eta \mathbf{H}\), where \(\mathbf{H}\) is the average of \(\tilde{\mathbf{x}}\tilde{\mathbf{x}}^\top\) over the training set. Compute the eigenvalues of \(\mathbf{H}\) 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 \(10^{-3}\).
- Show that a step on a single example multiplies the component of the parameter error along \(\tilde{\mathbf{x}}\) by \(1 - \eta \|\tilde{\mathbf{x}}\|^2\), and use \(\mathbb{E}\|\tilde{\mathbf{x}}\|^2 = 3\) 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 \((\mathbf{w}, b)\) 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 \(y^{(5)} = 10{,}000\), the corruption used in Section 2.1.1.3, and train with both losses. Record \(b\) 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
\[l_\delta(y, y') = \begin{cases}\frac{1}{2}(y-y')^2 & \textrm{ if } |y-y'| \leq \delta \\ \delta \left(|y-y'| - \frac{\delta}{2}\right) & \textrm{ otherwise,}\end{cases} \tag{2.3.5}\]
whose quadratic part matches the squared loss of this section. Train for \(\delta \in \{1, 10, 10^2, 10^3, 10^4\}\), and plot the distance \(|\hat{b} - b^*|\) of the learned bias from the generating bias \(b^* = 4.2\) against \(\delta\) on logarithmic axes. Explain the shape of the curve from the derivative of \(l_\delta\) with respect to \(y'\), and relate the result to the penalty curves of Figure 2.1.6.
- [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 Equation 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 \(3 \times 3\) Hessian of the minibatch loss with respect to \(\boldsymbol{\theta} = (\mathbf{w}, b)\), and state which quantities it depends on. Then compute it with automatic differentiation by recording the gradient inside an outer
tf.GradientTapeand callingjacobian(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 Equation 2.3.4.
[code] Stability and minibatch size. ● The expected loss predicts that steps along its gradient diverge for \(\eta > 2\). Let \(\tilde{\mathbf{x}} = (\mathbf{x}, 1)\) be an input with a \(1\) 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 \(\mathbf{I} - \eta \mathbf{H}\), where \(\mathbf{H}\) is the average of \(\tilde{\mathbf{x}}\tilde{\mathbf{x}}^\top\) over the training set. Compute the eigenvalues of \(\mathbf{H}\) 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 \(10^{-3}\).
- Show that a step on a single example multiplies the component of the parameter error along \(\tilde{\mathbf{x}}\) by \(1 - \eta \|\tilde{\mathbf{x}}\|^2\), and use \(\mathbb{E}\|\tilde{\mathbf{x}}\|^2 = 3\) 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 \((\mathbf{w}, b)\) 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 \(y^{(5)} = 10{,}000\), the corruption used in Section 2.1.1.3, and train with both losses. Record \(b\) 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
\[l_\delta(y, y') = \begin{cases}\frac{1}{2}(y-y')^2 & \textrm{ if } |y-y'| \leq \delta \\ \delta \left(|y-y'| - \frac{\delta}{2}\right) & \textrm{ otherwise,}\end{cases}\]
whose quadratic part matches the squared loss of this section. Train for \(\delta \in \{1, 10, 10^2, 10^3, 10^4\}\), and plot the distance \(|\hat{b} - b^*|\) of the learned bias from the generating bias \(b^* = 4.2\) against \(\delta\) on logarithmic axes. Explain the shape of the curve from the derivative of \(l_\delta\) with respect to \(y'\), and relate the result to the penalty curves of Figure 2.1.6.
- [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 Equation 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 \(3 \times 3\) Hessian of the minibatch loss with respect to \(\boldsymbol{\theta} = (\mathbf{w}, b)\), and state which quantities it depends on. Then compute it with automatic differentiation via
jax.hessian(orjax.jacrev(jax.grad(...)), 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 Equation 2.3.4.
[code] Stability and minibatch size. ● The expected loss predicts that steps along its gradient diverge for \(\eta > 2\). Let \(\tilde{\mathbf{x}} = (\mathbf{x}, 1)\) be an input with a \(1\) 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 \(\mathbf{I} - \eta \mathbf{H}\), where \(\mathbf{H}\) is the average of \(\tilde{\mathbf{x}}\tilde{\mathbf{x}}^\top\) over the training set. Compute the eigenvalues of \(\mathbf{H}\) 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 \(10^{-3}\).
- Show that a step on a single example multiplies the component of the parameter error along \(\tilde{\mathbf{x}}\) by \(1 - \eta \|\tilde{\mathbf{x}}\|^2\), and use \(\mathbb{E}\|\tilde{\mathbf{x}}\|^2 = 3\) 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 \((\mathbf{w}, b)\) 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 \(y^{(5)} = 10{,}000\), the corruption used in Section 2.1.1.3, and train with both losses. Record \(b\) 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
\[l_\delta(y, y') = \begin{cases}\frac{1}{2}(y-y')^2 & \textrm{ if } |y-y'| \leq \delta \\ \delta \left(|y-y'| - \frac{\delta}{2}\right) & \textrm{ otherwise,}\end{cases}\]
whose quadratic part matches the squared loss of this section. Train for \(\delta \in \{1, 10, 10^2, 10^3, 10^4\}\), and plot the distance \(|\hat{b} - b^*|\) of the learned bias from the generating bias \(b^* = 4.2\) against \(\delta\) on logarithmic axes. Explain the shape of the curve from the derivative of \(l_\delta\) with respect to \(y'\), and relate the result to the penalty curves of Figure 2.1.6.
- [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 Equation 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 \(3 \times 3\) Hessian of the minibatch loss with respect to \(\boldsymbol{\theta} = (\mathbf{w}, b)\), and state which quantities it depends on. Because MXNet’s
autogradsupports first-order reverse-mode differentiation (Section 1.5), assemble the three columns of the Hessian by central differences of the autograd gradient \((\nabla L(\boldsymbol{\theta} + h\mathbf{e}_j) - \nabla L(\boldsymbol{\theta} - h\mathbf{e}_j)) / (2h)\) 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 Equation 2.3.4.
[code] Stability and minibatch size. ● The expected loss predicts that steps along its gradient diverge for \(\eta > 2\). Let \(\tilde{\mathbf{x}} = (\mathbf{x}, 1)\) be an input with a \(1\) 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 \(\mathbf{I} - \eta \mathbf{H}\), where \(\mathbf{H}\) is the average of \(\tilde{\mathbf{x}}\tilde{\mathbf{x}}^\top\) over the training set. Compute the eigenvalues of \(\mathbf{H}\) 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 \(10^{-3}\).
- Show that a step on a single example multiplies the component of the parameter error along \(\tilde{\mathbf{x}}\) by \(1 - \eta \|\tilde{\mathbf{x}}\|^2\), and use \(\mathbb{E}\|\tilde{\mathbf{x}}\|^2 = 3\) 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 \((\mathbf{w}, b)\) 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 \(y^{(5)} = 10{,}000\), the corruption used in Section 2.1.1.3, and train with both losses. Record \(b\) 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
\[l_\delta(y, y') = \begin{cases}\frac{1}{2}(y-y')^2 & \textrm{ if } |y-y'| \leq \delta \\ \delta \left(|y-y'| - \frac{\delta}{2}\right) & \textrm{ otherwise,}\end{cases}\]
whose quadratic part matches the squared loss of this section. Train for \(\delta \in \{1, 10, 10^2, 10^3, 10^4\}\), and plot the distance \(|\hat{b} - b^*|\) of the learned bias from the generating bias \(b^* = 4.2\) against \(\delta\) on logarithmic axes. Explain the shape of the curve from the derivative of \(l_\delta\) with respect to \(y'\), and relate the result to the penalty curves of Figure 2.1.6.