2  Linear Regression

Regression is the workhorse of quantitative prediction whenever the target is a meaningful number rather than a discrete category: estimating a home’s sale price from its floor area and age, forecasting a patient’s hospital stay from vital signs, or predicting next quarter’s electricity demand. It is also an ideal proving ground for deep learning. Nearly every ingredient of neural network training—parameterized forward passes, loss functions grounded in maximum likelihood, minibatch stochastic gradient descent, reusable training harnesses, generalization diagnostics, and weight-norm regularization—already appears in its simplest, most transparent form in linear regression.

We begin in Section 2.1 by formulating the affine model and the squared error loss, solving the problem both in closed form via orthogonal projection and iteratively via minibatch stochastic gradient descent (SGD), and connecting squared loss to Gaussian maximum likelihood. Before touching real data, Section 2.2 constructs a synthetic benchmark with known ground-truth parameters \((\mathbf{w}^*, b^*)\) and noise level \(\sigma\), giving us an exact target against which to test our code. The next three sections build the training pipeline in stages: first from raw tensors and automatic differentiation (Section 2.3), then factored into the reusable Module, DataModule, and Trainer classes that power the rest of the book (Section 2.4), and finally expressed in a few lines with high-level framework layers and optimizers (Section 2.5).

Fitting the training data is only half the problem. Using polynomial curve fitting, Section 2.6 separates training error from generalization error, decomposes expected test error into squared bias, variance, and noise, and shows how validation splits and \(K\)-fold cross-validation select model complexity without peeking at test data. Finally, Section 2.7 tames overfitting in high dimensions by adding a squared \(\ell_2\) penalty, showing how weight decay selectively shrinks directions that the training inputs determine poorly.