Search

Search papers and lessons

Penalized Least Squares

Level 3 · 12 min read

Penalized least squares fits a linear model by minimising squared errors plus a penalty on the weights, and its solution is one formula that stays stable when the inputs are correlated.

On this page

  • Colour = topic mix
  • Calculus
  • Discrete math
  • Linear algebra
  • Probability
  • Losses & regularization
  • Learning basics
  • Sign in to see your progress

TL;DR

Penalized least squares is Linear Regression with a price on large weights. It picks the weights that make the squared errors on the training data small and the weights themselves small, at the same time. The price is the penalty from L2 Regularization, and its strength is a number you choose before fitting, called a hyperparameter.

The best weights have a closed form. The penalty adds a constant to the diagonal of the matrix that must be inverted (see Matrix Inverse), so the formula still works when the inputs are so correlated that ordinary least squares breaks down.

Where you'll see it: ridge regression in statistics software, the weight_decay setting when training neural networks, and as the building block of Kernel Ridge Regression.

Intuition

The question

Ordinary least squares asks which weights make the predictions closest to the targets. With plenty of data and inputs that carry different information, the answer is stable. Trouble starts when two inputs say nearly the same thing. Height in centimetres and height in inches carry the same information, so the fit cannot tell which one deserves credit. It may give one a large positive weight and the other a large negative weight. On the training data these cancel out nicely. On new data, where the two inputs drift apart, the predictions swing wildly.

Penalized least squares asks a different question: which weights fit the data well and are also small? You decide how much a unit of weight size is worth. A small price gives something close to ordinary least squares. A large price pulls every weight toward zero.

Shrinkage in one number

Take a single input with no intercept. Ordinary least squares gives a weight w0w_0. With the penalty, the weight becomes w0w_0 multiplied by a factor ss+λ\frac{s}{s+\lambda}, where ss is the sum of the squared inputs and λ\lambda is the penalty strength. That factor always lies between 0 and 1. The weight shrinks, but it never flips sign.

0510152000.20.40.60.81penalty strength λshrink factor
  • s = 5
  • s = 20
The shrink factor s/(s+λ). A larger s (more data or larger inputs) makes the data resist the penalty more. A larger λ shrinks harder. The two marked points are where λ equals s, and the factor is one half.

The math

The penalized objective

Definition: Penalized least squares objective

Given nn training examples, stack the inputs as the rows of a matrix XX of size n×dn \times d, and the targets as a vector y\mathbf{y}. For a weight vector w∈Rd\mathbf{w} \in \mathbb{R}^d and a strength λ≥0\lambda \ge 0, the objective is

J(w)=∥Xw−y∥2+λ∥w∥2.J(\mathbf{w}) = \|X\mathbf{w} - \mathbf{y}\|^2 + \lambda \|\mathbf{w}\|^2.

The solution is the w^\hat{\mathbf{w}} that minimises JJ.

The first term is the sum of squared errors: XwX\mathbf{w} holds the nn predictions, and the squared length of the difference from y\mathbf{y} is the total squared miss. The second term is the penalty, the squared length of the weight vector (see Vector Norm). The number λ\lambda is not fitted from the data. You choose it, usually by checking performance on held-out data with Cross-Validation.

The intercept is normally left out of the penalty. The simple way to do this is to centre the inputs and targets first, by subtracting their means. After centring, the intercept is just the mean of y\mathbf{y}, and the penalised fit uses only the slopes.

The closed-form solution

Expand the objective. Writing w⊤\mathbf{w}^\top for the transpose of w\mathbf{w}:

J(w)=w⊤X⊤Xw−2 w⊤X⊤y+y⊤y+λ w⊤w.J(\mathbf{w}) = \mathbf{w}^\top X^\top X \mathbf{w} - 2\,\mathbf{w}^\top X^\top \mathbf{y} + \mathbf{y}^\top \mathbf{y} + \lambda\, \mathbf{w}^\top \mathbf{w}.

Take the gradient with respect to w\mathbf{w}. For a symmetric matrix AA, the gradient of w⊤Aw\mathbf{w}^\top A \mathbf{w} is 2Aw2A\mathbf{w}, and the gradient of −2 w⊤b-2\,\mathbf{w}^\top \mathbf{b} is −2b-2\mathbf{b}. So

∇J(w)=2X⊤Xw−2X⊤y+2λw.\nabla J(\mathbf{w}) = 2X^\top X \mathbf{w} - 2X^\top \mathbf{y} + 2\lambda \mathbf{w}.

Set the gradient to zero and move the w\mathbf{w} terms to one side. The identity matrix II (ones on the diagonal, zeros elsewhere) lets us write λw=λIw\lambda \mathbf{w} = \lambda I \mathbf{w}:

(X⊤X+λI)w^=X⊤y⟹w^=(X⊤X+λI)−1X⊤y.\left(X^\top X + \lambda I\right)\hat{\mathbf{w}} = X^\top \mathbf{y} \quad\Longrightarrow\quad \hat{\mathbf{w}} = \left(X^\top X + \lambda I\right)^{-1} X^\top \mathbf{y}.

The formula is ordinary least squares with λI\lambda I added to X⊤XX^\top X. Why is the inverse safe? The matrix X⊤XX^\top X never has negative eigenvalues. Adding λI\lambda I with λ>0\lambda \gt 0 moves every eigenvalue up by λ\lambda, so none of them is zero. A matrix with no zero eigenvalue is invertible, so the solution always exists, even when X⊤XX^\top X is singular.

What the penalty does in each direction

Write the inputs with a Singular Value Decomposition (SVD), X=UΣV⊤X = U\Sigma V^\top, where σ1,σ2,…\sigma_1, \sigma_2, \dots are the singular values on the diagonal of Σ\Sigma. Substituting into the formula gives

w^=V diag ⁣(σiσi2+λ)U⊤y.\hat{\mathbf{w}} = V\, \mathrm{diag}\!\left(\frac{\sigma_i}{\sigma_i^2 + \lambda}\right) U^\top \mathbf{y}.

Each direction in the input space is scaled by σiσi2+λ\frac{\sigma_i}{\sigma_i^2+\lambda}. When σi\sigma_i is large (the data varies strongly along that direction), the factor is close to 1/σi1/\sigma_i, the ordinary answer. When σi\sigma_i is small (the data barely varies there, which is what correlated inputs produce), the factor is pulled toward zero. So the penalty acts mainly on the directions the data cannot pin down.

A Bayesian reading

If the noise in the targets is Gaussian (see Gaussian (Normal) Distribution) and the weights have a Gaussian prior centred at zero, then the most probable weights, the MAP estimate, are exactly the minimiser of JJ. The strength is λ=σnoise2/τ2\lambda = \sigma_{\text{noise}}^2 / \tau^2, where σnoise\sigma_{\text{noise}} is the noise size and τ\tau is the prior's spread. A strong belief that weights are small means a large λ\lambda.

Worked examples

Example
Example 1: one input, two points (hand-computable)

Data: x=(1,2)x = (1, 2) and y=(2,4)y = (2, 4). One input, no intercept.

  1. Sums: ∑x2=1+4=5\sum x^2 = 1 + 4 = 5 and ∑xy=1⋅2+2⋅4=10\sum xy = 1 \cdot 2 + 2 \cdot 4 = 10.
  2. Objective for one weight ww: J(w)=(2−w)2+(4−2w)2+λw2J(w) = (2 - w)^2 + (4 - 2w)^2 + \lambda w^2.
  3. Derivative: −2(2−w)−4(4−2w)+2λw=10w−20+2λw-2(2 - w) - 4(4 - 2w) + 2\lambda w = 10w - 20 + 2\lambda w. Set it to zero: w=2010+2λ=105+λw = \frac{20}{10 + 2\lambda} = \frac{10}{5 + \lambda}.
  4. No penalty, λ=0\lambda = 0: w=2w = 2. This is exact, since y=2xy = 2x for both points.
  5. λ=5\lambda = 5: w=10/10=1w = 10/10 = 1. The weight is halved.
  6. λ=20\lambda = 20: w=10/25=0.4w = 10/25 = 0.4. The weight keeps shrinking but never reaches zero.

Interpretation: the penalty trades fit for size. The data alone wants slope 2, and each larger λ\lambda asks for a smaller slope.

Example
Example 2: a textbook case with 5 points

Centred data: x=(−2,−1,0,1,2)x = (-2, -1, 0, 1, 2) and y=(−3.9,−2.1,0.1,1.9,4.1)y = (-3.9, -2.1, 0.1, 1.9, 4.1). The true slope is about 2.

  1. ∑x2=4+1+0+1+4=10\sum x^2 = 4 + 1 + 0 + 1 + 4 = 10, so s=10s = 10.
  2. ∑xy=(−2)(−3.9)+(−1)(−2.1)+0+(1)(1.9)+(2)(4.1)=7.8+2.1+1.9+8.2=20.0\sum xy = (-2)(-3.9) + (-1)(-2.1) + 0 + (1)(1.9) + (2)(4.1) = 7.8 + 2.1 + 1.9 + 8.2 = 20.0.
  3. Ordinary weight: w0=20.0/10=2.0w_0 = 20.0 / 10 = 2.0.
  4. Penalized weight: w=20.010+λw = \frac{20.0}{10 + \lambda}. Check with the shrink factor: w=w0⋅ss+λw = w_0 \cdot \frac{s}{s+\lambda} gives the same value.
  5. λ=2\lambda = 2: w=20/12≈1.67w = 20/12 \approx 1.67. The shrink factor is 10/12≈0.8310/12 \approx 0.83.
  6. λ=10\lambda = 10: w=20/20=1.0w = 20/20 = 1.0. The shrink factor is 10/20=0.510/20 = 0.5, so the slope is halved.

Interpretation: a penalty of 10 is as strong as the data's own spread of inputs, and it cuts the slope in half. A penalty of 2 barely moves it.

Example
Example 3: two identical inputs (where ordinary least squares fails)

Let the two inputs be the same column, so X=(111122)X = \begin{pmatrix} 1 & 1 \\ 1 & 1 \\ 2 & 2 \end{pmatrix}, with targets y=(1,1,2)⊤\mathbf{y} = (1, 1, 2)^\top.

  1. X⊤X=(6666)X^\top X = \begin{pmatrix} 6 & 6 \\ 6 & 6 \end{pmatrix} and X⊤y=(6,6)⊤X^\top \mathbf{y} = (6, 6)^\top.
  2. Its determinant is 36−36=036 - 36 = 0, so X⊤XX^\top X has no inverse. Any weights with w1+w2=1w_1 + w_2 = 1 fit the data exactly, so ordinary least squares has no single answer.
  3. With the penalty: X⊤X+λI=(6+λ666+λ)X^\top X + \lambda I = \begin{pmatrix} 6 + \lambda & 6 \\ 6 & 6 + \lambda \end{pmatrix}. The two weights must be equal by symmetry, so w1=w2=ww_1 = w_2 = w, and the first row gives (6+λ)w+6w=6(6 + \lambda)w + 6w = 6. So w=612+λw = \frac{6}{12 + \lambda}.
  4. λ=0\lambda = 0: the limit gives w=0.5w = 0.5 for each weight. Among all weights with w1+w2=1w_1 + w_2 = 1, this pair has the smallest total squared size, so the penalty chooses it in the limit.
  5. λ=1\lambda = 1: w=6/13≈0.4615w = 6/13 \approx 0.4615. Check: 7⋅0.4615+6⋅0.4615=6.07 \cdot 0.4615 + 6 \cdot 0.4615 = 6.0.

Interpretation: the penalty splits the weight evenly between the two copies and gives a unique answer. Ordinary least squares could not decide.

Example
Example 4: a realistic setting, choosing the strength

Suppose one standardised input is observed 50 times, so s=∑x2=50s = \sum x^2 = 50. A validation set would decide between several strengths. The shrink factors below are exact values of ss+λ\frac{s}{s+\lambda}. The choice itself depends on your data, so no error figures are given here.

Strength λ\lambdaShrink factor 5050+λ\frac{50}{50+\lambda}What it does
01.000Ordinary least squares
10.980Almost no change
100.833Mild shrinkage
500.500Slope halved
2000.200Strong shrinkage, risk of underfitting

Procedure: fit on the training set for each λ\lambda in a log-spaced grid, measure the validation error, and keep the λ\lambda with the smallest error. With many inputs, the same procedure applies to the full formula (X⊤X+λI)−1X⊤y(X^\top X + \lambda I)^{-1} X^\top \mathbf{y}.

Tradeoffs and failure modes

SituationProblemBetter choice
Many correlated inputsOrdinary weights are unstable and cancel each otherPenalized least squares
You want many weights exactly zeroRidge keeps every input, only shrinking itLasso Regression
Strength too largeThe model underfits, with high biasLower λ\lambda on validation data
Strength zero with more inputs than examplesThe fit is not unique and overfitsUse a positive λ\lambda
Inputs on different scalesThe penalty treats a large-unit input as cheap and a small-unit one as expensiveStandardise the inputs first
Intercept left in the penaltyThe mean level of the targets gets shrunk toward zeroCentre the data, or leave the intercept out of the penalty
The true relation is curvedA linear model cannot follow itKernel Ridge Regression
Very many inputsInverting a d×dd \times d matrix costs roughly d3d^3 operationsIterative solvers such as Gradient Descent

The penalty is not free. Shrinking a weight biases its estimate toward zero. That bias is worth paying when it buys a large drop in variance, which is the usual case with noisy or correlated data.

History

Arthur Hoerl and Robert Kennard published the ridge estimator in 1970, in the journal Technometrics. Their paper, "Ridge regression: biased estimation for nonorthogonal problems", was motivated by least squares estimates that swung wildly when the predictors were nearly collinear. Their remedy was to add a constant to the diagonal of the matrix before inverting it, which is exactly the formula above.

A similar idea appeared in the mathematics of ill-posed problems. Andrey Tikhonov developed the general form of this kind of penalty in the 1960s, and the penalty is often called Tikhonov regularization in that setting. Statisticians and mathematicians were, in effect, solving the same problem from two directions.

The idea caught on for two reasons. It is a single parameter with a closed-form answer, which made it cheap to compute before fast hardware. And it has a clean Bayesian meaning, which tied it to probability. Later, neural network researchers reused the same penalty under the name weight decay, and it remains a standard setting today.

Recap

A linear model fits the training data by minimising squared error. Adding λ∥w∥2\lambda \|\mathbf{w}\|^2 to the loss shrinks the weights, and the solution is (X⊤X+λI)−1X⊤y(X^\top X + \lambda I)^{-1} X^\top \mathbf{y}. The added λI\lambda I makes the inverse exist even when the inputs are correlated. You choose λ\lambda with validation data. The natural next steps are Lasso Regression, which penalises the absolute size of weights and so sets some to zero, and Kernel Ridge Regression, which applies the same idea to curved relationships.

Check yourself

QuestionRecall: what are the two terms of the penalized least squares objective, and what does λ\lambda control?Show answer

The first term, ∥Xw−y∥2\|X\mathbf{w} - \mathbf{y}\|^2, is the sum of squared errors on the training data. The second, λ∥w∥2\lambda \|\mathbf{w}\|^2, is the penalty on the squared size of the weights. The strength λ≥0\lambda \ge 0 sets the price of a large weight: λ=0\lambda = 0 gives ordinary least squares, and larger values shrink the weights harder.

QuestionComputation: for one input with ∑x2=10\sum x^2 = 10 and ∑xy=20\sum xy = 20, what is the penalized weight when λ=10\lambda = 10?Show answer

The formula for one input is w=∑xy∑x2+λ=2010+10=1w = \frac{\sum xy}{\sum x^2 + \lambda} = \frac{20}{10 + 10} = 1. The ordinary weight would be 20/10=220/10 = 2, so the penalty halves it.

QuestionWhy: why does adding λI\lambda I make the solution exist even when X⊤XX^\top X has no inverse?Show answer

X⊤XX^\top X never has negative eigenvalues. A singular matrix has an eigenvalue of zero. Adding λI\lambda I with λ>0\lambda \gt 0 shifts every eigenvalue up by λ\lambda, so none is zero. A matrix with no zero eigenvalue is invertible, so (X⊤X+λI)−1(X^\top X + \lambda I)^{-1} exists and the solution is unique.

QuestionApplied: you have 1000 examples and 500 highly correlated inputs. Ordinary least squares gives coefficients in the hundreds, with pairs of opposite sign. What do you do, and what should happen to those pairs?Show answer

Fit penalized least squares, choosing λ\lambda by cross-validation over a log-spaced grid. The large coefficients should shrink, and the opposite-sign pairs should move toward each other, because the penalty favours spreading weight evenly across correlated inputs. Check that the validation error improves; if it does not, the linear model itself may be the limit.

Sources