Skip to content
ml-recall

Topic notes

Linear Models & Regularization

Least-squares linear models — the normal equations, reading coefficients and residuals, basis functions, ridge/lasso regularization, collinearity and the classical OLS assumptions.

5-min read AI-checked

Practise 91 questions Take a test

Key ideas

Model1. y^=w⊤x+b\hat y = \mathbf{w}^\top\mathbf{x} + b: with dd features the model learns dd weights plus one bias (2 features → 3 parameters). Training changes w\mathbf{w} and bb, never the features. Appending a constant feature 1 to every x\mathbf{x} folds the bias into w\mathbf{w} as its last weight; without a bias the fit is forced through the origin.

Least squares1. Each residual yi−y^iy_i - \hat y_i is squared — so errors above and below the line cannot cancel — and the squares are added up; the best w\mathbf{w} minimizes that sum. Setting the gradient to zero gives the normal equations, with a unique solution when the design matrix XX has full column rank. The loss is a convex quadratic, so gradient descent with a small enough step reaches the global minimum from any start (even all-zero weights); the closed form and gradient descent differ in cost, not in the model.

Probabilistic view1. If y=w⊤x+b+εy = \mathbf{w}^\top\mathbf{x} + b + \varepsilon with Gaussian ε\varepsilon, maximum likelihood is exactly least squares, whatever the noise variance. Laplace noise instead gives the absolute loss ∑i∣yi−y^i∣\sum_i |y_i - \hat y_i|. For a single constant, squared loss is minimized by the mean and absolute loss by the median — which is why squared loss is sensitive to outliers1. The absolute loss has a gradient of constant size, so SGD with a fixed step keeps bouncing around the optimum; the Huber loss (quadratic near 0, linear beyond a threshold) combines the two.

Reading a fit4. The slope is the predicted change in yy per unit of xx, in the units of both (price in $1000 and a slope of −1.25-1.25 per year of age: about $1,250 less per year); the intercept is the prediction at x=0x = 0. With an intercept, the least-squares line passes through (xˉ,yˉ)(\bar x, \bar y) and the residuals sum to zero; for one feature, R2=r2R^2 = r^2, so rr near ±1\pm 1 means a good straight-line fit4. Regression on observational data shows association, not causation. A coefficient's size depends on its feature's units and on correlated features, so compare coefficients only for standardized features — and even then correlated features blur the comparison.

Basis functions. Adding powers x2,x3,…x^2, x^3, \dots or products xixjx_ix_j gives polynomial regression: nonlinear in xx, still linear in w\mathbf{w}, so the same least-squares machinery applies. The degree is the complexity knob — too low underfits, too high overfits — and with more features than examples a linear model can fit its training data almost perfectly yet generalize badly2.

Regularization2,3

Collinearity3. If one feature is an exact combination of others (z=x+yz = x + y), XX loses rank, X⊤XX^\top X is singular and OLS has infinitely many solutions. Near-collinearity makes X⊤XX^\top X nearly singular, so the coefficients get large variances and can flip sign3; predictions within the range of the training data are much less affected. Forming X⊤XX^\top X also squares the condition number, κ(X⊤X)=κ(X)2\kappa(X^\top X) = \kappa(X)^2, so solvers work with QR or SVD factorizations of XX.

Classical assumptions5. With a model linear in its parameters, full column rank, and errors of zero mean, equal variance and no correlation with each other, OLS is the best linear unbiased estimator (Gauss–Markov). Normal errors are not needed for that — only for exact small-sample tt and FF tests. Correlated features are allowed; only perfect collinearity is excluded.

Formulas

X⊤X w^=X⊤y⇒w^=(X⊤X)−1X⊤y,w^ridge=(X⊤X+αI)−1X⊤yX^\top X\,\hat{\mathbf{w}} = X^\top\mathbf{y} \quad\Rightarrow\quad \hat{\mathbf{w}} = (X^\top X)^{-1}X^\top\mathbf{y}, \qquad \hat{\mathbf{w}}_{\text{ridge}} = (X^\top X + \alpha I)^{-1}X^\top\mathbf{y}

(The ridge formula assumes centered data, so that the intercept, yˉ\bar y, is not penalized.)

One feature4: b1=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2b_1 = \dfrac{\sum_i (x_i - \bar x)(y_i - \bar y)}{\sum_i (x_i - \bar x)^2},  b0=yˉ−b1xˉ\ b_0 = \bar y - b_1\bar x.

Gradient of 12∥Xw−y∥2+λ2∥w∥2\tfrac12\lVert X\mathbf{w} - \mathbf{y}\rVert^2 + \tfrac{\lambda}{2}\lVert\mathbf{w}\rVert^2 is X⊤Xw−X⊤y+λwX^\top X\mathbf{w} - X^\top\mathbf{y} + \lambda\mathbf{w}, so each gradient step first multiplies w\mathbf{w} by (1−ηλ)(1 - \eta\lambda) — weight decay2. An ℓ1\ell_1 step instead moves every non-zero weight toward 0 by the same ηλ\eta\lambda. With orthonormal features, the lasso soft-thresholds the OLS coefficients6; for 12∥y−Xβ∥2+λ∥β∥1\tfrac12\lVert\mathbf{y} - X\boldsymbol\beta\rVert^2 + \lambda\lVert\boldsymbol\beta\rVert_1 this gives βj=sign⁡(β^j)max⁡(∣β^j∣−λ,0)\beta_j = \operatorname{sign}(\hat\beta_j)\max(|\hat\beta_j| - \lambda, 0).

Worked example

Points (0,1),(1,3),(2,4),(3,8)(0, 1), (1, 3), (2, 4), (3, 8): xˉ=1.5\bar x = 1.5, yˉ=4\bar y = 4, ∑(xi−xˉ)(yi−yˉ)=11\sum (x_i - \bar x)(y_i - \bar y) = 11 and ∑(xi−xˉ)2=5\sum (x_i - \bar x)^2 = 5, so the slope is 2.22.2 and the intercept 4−2.2⋅1.5=0.74 - 2.2 \cdot 1.5 = 0.7. The fitted values 0.7,2.9,5.1,7.30.7, 2.9, 5.1, 7.3 leave residuals 0.3,0.1,−1.1,0.70.3, 0.1, -1.1, 0.7, which sum to 0 (and ∑irixi=0\sum_i r_ix_i = 0). With residual sum of squares 1.8 and total sum of squares 26, R2=1−1.8/26≈0.931R^2 = 1 - 1.8/26 \approx 0.931, equal to r2r^2.

Ridge with α=5\alpha = 5 and an unpenalized intercept: the slope becomes 11/(5+5)=1.111/(5 + 5) = 1.1 and the intercept 4−1.1⋅1.5=2.354 - 1.1 \cdot 1.5 = 2.35. The slope is halved, and the line still passes through (xˉ,yˉ)(\bar x, \bar y).

In code

import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import Lasso, LinearRegression, Ridge

X, y = make_regression(n_samples=60, n_features=8, n_informative=3,   # informative:
                       noise=5.0, random_state=0)                     # features 0, 2, 5
ols = LinearRegression().fit(X, y).coef_
ridge = Ridge(alpha=10.0).fit(X, y).coef_
lasso = Lasso(alpha=5.0).fit(X, y).coef_
print(ols.round(1))                      # [76.6 -0.7 88.1 -0.7  0.5 96.8  0.3  1.2]
print(ridge.round(1))                    # [64.   0.7 76.3 -3.9  0.1 81.1  1.4  3.4]
print(lasso.round(1) + 0.0)              # [70.1  0.  84.   0.   0.  91.8  0.   0. ]
print(np.sum(ridge == 0), np.sum(lasso == 0))   # 0 5  (exact zeros)

OLS gives the five useless features small non-zero weights, ridge shrinks all weights but keeps them non-zero, and lasso sets exactly those five to zero.

Common pitfalls

References

  1. Dive into Deep Learning — Sec. 3.1 Linear Regression (3.1.1 Basics, 3.1.3 The Normal Distribution and Squared Loss)
  2. Dive into Deep Learning — Sec. 3.7 Weight Decay (3.7.1 Norms and Weight Decay, 3.7.2 High-Dimensional Linear Regression)
  3. scikit-learn User Guide — Sec. 1.1 Linear Models (1.1.1 Ordinary Least Squares, 1.1.2 Ridge regression and classification, 1.1.3 Lasso, 1.1.5 Elastic-Net)
  4. Wikipedia: Simple linear regression — Formulation and computation; Interpretation; Numerical properties
  5. Wikipedia: Gauss–Markov theorem — Statement; Gauss–Markov theorem as stated in econometrics
  6. Wikipedia: Lasso (statistics) — Basic form (Orthonormal covariates); Interpretations (Bayesian interpretation); Generalizations (Elastic net)