Linear Regression Implementation from Scratch

Dive into Deep Learning · §2.3

Linear Regression Implementation from Scratch
tensor parameters · broadcasting guards · autograd verification · minibatch SGD loop · convergence floor

Why a Falling Loss Curve Never Proves Correctness

The Systems Debugging Hazard

  • Silent broadcasting bug: Subtracting a 1D label tensor y of shape (32,) from y_hat of shape (32, 1) broadcasts into a (32, 32) matrix of all 1{,}024 pairwise differences.
  • Deceptive loss curve: Minimizing the 32 \times 32 mean pulls predictions toward \bar{y}, causing loss to drop smoothly while \mathbf{w} \to \mathbf{0} instead of \mathbf{w}^* = (2, -3.4)^\top.
  • Dual verification: Always check both the validation loss floor (\frac{1}{2}\sigma^2 = 5 \times 10^{-5}) and parameter recovery (\|\hat{\mathbf{w}} - \mathbf{w}^*\|_\infty \lesssim 10^{-3}).

Initializing Parameters With Gradient Tracking

From-Scratch Setup

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, b
  • Gradient tracking: The parameters are created so that the framework can differentiate the loss with respect to them.

Forward Pass and the Defensive Reshape in Squared Loss

Model & Loss Primitives

def linreg(X, w, b):
    """The linear regression model."""
    return d2l.matmul(X, w) + b
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)
  • Defensive shape alignment: squared_loss calls d2l.reshape(y, (-1, 1)) before subtracting, guaranteeing an elementwise (32, 1) residual vector.

Verifying Autograd Against the Analytical Gradient

Gradient Check

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
  • Exact match: Comparing reverse-mode autograd against \nabla_{\mathbf{w}} L_{\mathcal{B}} = \frac{1}{|\mathcal{B}|}\mathbf{X}^\top\mathbf{r} and \partial_b L_{\mathcal{B}} = \frac{1}{|\mathcal{B}|}\mathbf{1}^\top\mathbf{r} confirms agreement to float32 machine epsilon (\sim 10^{-7}).

Why Reshuffling Every Epoch Is Essential for SGD

Stochastic Sampling Invariant

  • Unbiasedness requires random sampling: A uniformly sampled minibatch satisfies \mathbb{E}[\nabla L_{\mathcal{B}}] = \nabla L, with batch mean \bar{y}_{\mathcal{B}} \approx 4.2 \pm 0.7 stepping b steadily upward toward b^* = 4.2.
  • Pathology of sorted data: If examples are sorted by label, batch 1 holds the 32 most negative labels (\bar{y}_{\mathcal{B}} \approx -4.6), pushing b downward away from 4.2 and causing parameters to cycle wildly every epoch.

The Minibatch Generator and One-Pass Exhaustion

Data Iteration Pitfall

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]
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
  • Single-use generator exhaustion: A Python generator object runs out after one pass and yields 0 batches on a second for loop; call minibatches(...) fresh inside each epoch.

The Four-Step Update and Dozen-Line Training Loop

Complete From-Scratch Loop

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_losses
  • Autograd guard: The parameter update runs outside gradient recording, and each step uses only the current minibatch’s gradient.

Predicting the Convergence Rate Before Running Code

Quantitative Theory of the Loss Curve

\mathbb{E}\bigl[L(\mathbf{w}, b)\bigr] = \frac{1}{2}\|\mathbf{w} - \mathbf{w}^*\|_2^2 + \frac{1}{2}(b - b^*)^2 + \frac{1}{2}\sigma^2

  • Initial excess loss: Starting near (\mathbf{0}, 0), initial loss is \frac{1}{2}(2^2 + (-3.4)^2 + 4.2^2) \approx 16.6, over 5 orders of magnitude above the floor \frac{1}{2}\sigma^2 = 5 \times 10^{-5}.
  • Per-epoch contraction (32 steps at \eta = 0.03): Each step multiplies parameter error by (1 - \eta) = 0.97 and excess loss by 0.97^2, so one epoch shrinks excess loss by 0.97^{64} \approx 1/7 (7\times per epoch).

Training Run: Exponential Decay to the Noise Floor

Empirical Verification

Running train(lr=0.03) for 10 epochs confirms both the 7\times-per-epoch exponential slope and the plateau at the theoretical noise floor:

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

On a log-scale plot, exponential convergence (1 - \eta)^{64k} appears as a straight downward line for the first 7 epochs until the excess loss drops below the irreducible noise floor \sigma^2/2 = 5 \times 10^{-5}.

Verifying Parameter Recovery Toward (2, −3.4) and 4.2

Parameter Accuracy Check

error in w: 1.7e-04, 5.1e-04
error in b: -4.6e-04
  • Statistical vs. numerical error: Learned weights match (\mathbf{w}^*, b^*) within \sim \sigma / \sqrt{n} \approx 3.2 \times 10^{-4}.
  • Why loss alone is blind to 10^{-3} drift: A parameter drift of 5 \times 10^{-4} raises validation loss by only \sim 4 \times 10^{-7} (<1\% of the 5 \times 10^{-5} noise floor).

Learning-Rate Stability: Crawling vs. Divergence

Step-Size Limits

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
  • Stability boundary (0 < \eta < 2/\mu_{\max}): \eta = 0.003 crawls (loss \approx 2–3); \eta \in \{0.03, 0.3\} hits the 5 \times 10^{-5} floor; \eta = 3 > 2 multiplies error by 1 - 3 = -2 per step and overflows to nan.

Concept Check: Gradients, Loss Scaling & Stability

Check Your Understanding

Test your understanding of training loop mechanics on these three scenarios:

  1. Forgotten zero_grad(): If you omit param.grad.zero_() inside the training loop, what vector does step t subtract from param, and how do the iterates behave on a quadratic bowl?
  2. Summed loss vs. mean loss: Suppose a loss function computes the sum \sum_{i \in \mathcal{B}} (\hat{y}^{(i)} - y^{(i)})^2 over a minibatch of |\mathcal{B}| = 32 without dividing by 2|\mathcal{B}|. Which learning rate \eta reproduces our scratch step at \eta_{\textrm{scratch}} = 0.03?
  3. Rescaled feature stability: If you multiply feature x_1 by 10 (so its variance becomes 100 instead of 1), what happens to the maximum stable learning rate \eta_{\max}?

Answers:

  1. Without clearing, step t subtracts \eta \sum_{s=1}^t \mathbf{g}_s (the running sum of all past gradients), acting like undiscounted momentum that overshoots the minimum and oscillates without converging.
  2. The summed loss is 2|\mathcal{B}| = 64 times larger than our scratch loss, so its gradient is 64\mathbf{g}; we must divide the learning rate by 64 to \eta = 0.03 / 64 \approx 4.69 \times 10^{-4}.
  3. Scaling x_1 by 10 increases the largest eigenvalue of the Hessian \mathbf{H} = \frac{1}{n}\mathbf{X}^\top\mathbf{X} by 10^2 = 100, shrinking the stability ceiling \eta_{\max} = 2 / \mu_{\max} by 100\times (from \approx 2 down to \approx 0.02).

Summary & Key Takeaways

Summary

Training Stage Mathematical Operation Systems / Implementation Guard Quantitative Check (\sigma = 0.01, n = 1000)
1. Forward & Loss \hat{\mathbf{y}} = \mathbf{X}\mathbf{w} + b, L_{\mathcal{B}} = \frac{1}{2|\mathcal{B}|}\|\hat{\mathbf{y}} - \mathbf{y}\|_2^2 Reshape y to (-1, 1) to prevent (B,) - (B, 1) -> (B, B) broadcasting Initial loss \mathbb{E}[L(\mathbf{0}, 0)] \approx 16.6
2. Backward Pass \nabla_{\mathbf{w}} L_{\mathcal{B}} = \frac{1}{|\mathcal{B}|}\mathbf{X}^\top(\hat{\mathbf{y}} - \mathbf{y}) Verify autograd against hand formula on 1 batch Max discrepancy \lesssim 10^{-7} (float32 eps)
3. SGD Update (\mathbf{w}, b) \leftarrow (\mathbf{w}, b) - \eta \nabla L_{\mathcal{B}} Run update outside the autograd tape; use only the current gradient Stable for 0 < \eta < 2/\mu_{\max}; \eta=0.03 drops loss 7\times/epoch
4. Epoch Reshuffle Uniform permutation of \{0, \ldots, n-1\} Re-create generator each epoch so it does not exhaust after epoch 1 Loss plateaus at \sigma^2/2 = 5 \times 10^{-5}; \|\hat{\mathbf{w}} - \mathbf{w}^*\|_\infty \lesssim 10^{-3}

Up next (object-oriented design & concise implementation): We first package this bare loop into reusable Module, DataModule, and Trainer classes (LinearRegressionScratch), and then swap in high-level framework layers, MSE losses, and optimizers (LinearRegression).