Concise Implementation of Linear Regression

Dive into Deep Learning · §2.5

Concise Implementation of Linear Regression
framework layers · lazy shape inference · MSE loss scaling · built-in optimizers · Trainer reuse

Why Move From Scratch Code to Concise Framework APIs?

Scaling Up to Deep Networks

  • Hardware-tuned layers: Replace manual w, b allocation and matmul(X, w) + b with the framework’s single dense layer.
  • Tested losses & optimizers: Replace manual squared_loss and parameter loops with the framework’s built-in MSE and SGD.
  • Zero Trainer changes: Reuses the exact same SyntheticRegressionData and d2l.Trainer from the object-oriented design section.

Concise Model: A Single Fully Connected Layer

Framework Layer API

class LinearRegression(d2l.Module):
    """Linear regression built from framework components."""
    def __init__(self, lr):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.LazyLinear(1)

    def weight_init(self, module):
        if isinstance(module, nn.Linear):
            nn.init.normal_(module.weight, std=0.01)
            nn.init.zeros_(module.bias)
  • Inherited forward & lazy shape inference: d2l.Module.forward(X) delegates directly to self.net(X); the framework’s dense layer infers input dimension d = 2 automatically on the first minibatch.

Parameter Initialization: Small Gaussian Weights, Zero Bias

Weight & Bias Initialization

  • Lazy layer (LazyLinear): Materialize shapes with a dummy call model(data.X[:1]), then apply normal_(0, 0.01) to the weight and zeros_ to the bias.
data = d2l.SyntheticRegressionData(w=d2l.tensor([2, -3.4]), b=4.2)
model = LinearRegression(lr=0.015)
model(data.X[:1])  # Creates the parameters of the lazy layer
model.net.apply(model.weight_init)
trainer = d2l.Trainer(max_epochs=10)
trainer.board.yscale = 'log'
trainer.fit(model, data)

Framework MSE Loss and Halving the Learning Rate

Loss Scaling & Hyperparameter Coupling

def loss(self, y_hat, y):
    fn = nn.MSELoss()
    return fn(y_hat, y)
  • Why halve \eta from 0.03 to 0.015: Standard framework MSE omits our \frac{1}{2} factor, doubling both the loss value (floor \sigma^2 = 10^{-4}) and its gradient (2\mathbf{g}); halving \eta = 0.015 makes -\eta(2\mathbf{g}) = -0.03\mathbf{g} identical to our scratch step.

Configuring the Built-In Framework Optimizer

Optimizer Abstraction

def configure_optimizers(self):
    return torch.optim.SGD(self.parameters(), self.lr)
  • Automatic parameter discovery: The framework collects every registered parameter by traversing the module tree, so the optimizer needs no hand-made list of tensors.

Training and Parameter Recovery With Framework Parts

End-to-End Concise Execution

Fitting LinearRegression(lr=0.015) with d2l.Trainer(max_epochs=10) reproduces the exact 7\times-per-epoch convergence and O(10^{-4}) parameter recovery:

data = d2l.SyntheticRegressionData(w=d2l.tensor([2, -3.4]), b=4.2)
model = LinearRegression(lr=0.015)
model(data.X[:1])  # Creates the parameters of the lazy layer
model.net.apply(model.weight_init)
trainer = d2l.Trainer(max_epochs=10)
trainer.board.yscale = 'log'
trainer.fit(model, data)
validation loss: 1.01e-04
  • Floor at \sigma^2 = 10^{-4}: Because framework MSE omits the \frac{1}{2} factor, the loss settles at \sigma^2 = 10^{-4} (whose square root \sqrt{10^{-4}} = 0.01 = \sigma gives the root-mean-square prediction error in label units).

Extracting and Verifying the Learned Layer Parameters

Inspecting Framework Layer Weights

def get_w_b(self):
    return self.net.weight.detach(), self.net.bias.detach()
error in w: -2.1e-04, 9.5e-04
error in b: -1.1e-03
  • Matching ground truth: Both weights and bias match (\mathbf{w}^*, b^*) within a few \sigma / \sqrt{n} \approx 3 \times 10^{-4}.

Three Levels of Abstraction: Scratch → OO Scratch → Concise

The Chapter’s Pedagogical Progression

  • Bare Functions: Raw tensors w, b, manual linreg & squared_loss, a manual backward pass, and a one-pass minibatches generator.
  • OO Scratch (LinearRegressionScratch): Wraps raw tensors and custom SGD(lr=0.03) inside d2l.Module, trained via SyntheticRegressionData and d2l.Trainer.
  • Concise (LinearRegression): Swaps in framework dense layers, built-in MSE, and built-in SGD(lr=0.015) while reusing DataModule and Trainer unchanged.

Concept Check: Loss Scaling, Missing Bias & Multi-Output

Check Your Understanding

Test your understanding of framework layer and loss conventions on these three questions:

  1. Why the concise loss plateaus twice as high: Why does our concise run plateau near 10^{-4} while our scratch run plateaued near 5 \times 10^{-5} on the exact same synthetic generator?
  2. Omitting the bias (bias=False): If you disable the bias in LinearRegression on our dataset (b^* = 4.2, zero-mean features \mathbf{x} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}_2)), what value does the validation MSE plateau at?
  3. Two-output MSE scaling: If LinearRegression predicts 2 outputs instead of 1, framework MSE averages over all 2|\mathcal{B}| entries of the residual matrix. How does that affect each output’s gradient and equivalent learning rate?

Answers:

  1. Framework MSE computes \frac{1}{|\mathcal{B}|}\|\hat{\mathbf{y}} - \mathbf{y}\|_2^2 without our \frac{1}{2} factor, so at the true parameters its expected value is \mathbb{E}[\epsilon^2] = \sigma^2 = (0.01)^2 = 10^{-4} rather than \frac{1}{2}\sigma^2 = 5 \times 10^{-5}.
  2. Because \mathbb{E}[\mathbf{x}] = \mathbf{0}, the weights still converge near \mathbf{w}^* = (2, -3.4)^\top, while the unmodeled intercept b^* = 4.2 remains in every residual, raising the MSE floor to (b^*)^2 + \sigma^2 = 4.2^2 + 10^{-4} \approx 17.64.
  3. Dividing by 2|\mathcal{B}| instead of |\mathcal{B}| halves the gradient with respect to each output’s parameters, so doubling the learning rate to \eta = 0.03 restores the single-output step size.

Summary & Key Takeaways

Summary

Component From-Scratch Concise Framework Key Invariant / Takeaway
Model & Parameters LinearRegressionScratch (self.w, self.b) LinearRegression (the framework’s dense layer) Inherits Module.forward(X) -> self.net(X)
Loss Function \frac{1}{2|\mathcal{B}|}\|\hat{\mathbf{y}} - \mathbf{y}\|_2^2 Built-in MSE Omits 1/2 \implies loss & gradient are 2\times larger
Optimizer & Step Size Custom SGD at \eta = 0.03 Built-in SGD at \eta = 0.015 Halving \eta preserves the exact parameter update -\eta\nabla L
Noise Floor & Recovery Floor \sigma^2/2 = 5 \times 10^{-5} Floor \sigma^2 = 10^{-4} (\sqrt{\text{MSE}} = \sigma = 0.01) Both recover (\mathbf{w}^*, b^*) within \sim 3\sigma/\sqrt{n} \approx 10^{-3}