08 / 27 · Linear Regression
Regularization
Adding a penalty on the size of the weights to least squares: ridge regression, its closed form and its shrinkage of the unstable directions, the prior behind each penalty, the constrained form and why an L1 ball produces exact zeros, the lasso with soft thresholding, coordinate descent and its path, the elastic net for correlated features, and choosing the penalty's strength by cross-validation.
Least squares · Validation and overfitting · Bayesian inference
On this page 7
The optimizers note finished the machinery: least squares can be fitted for any number of examples and features. Fitting it is not the problem any more; trusting the fit is. The least-squares note showed two nearly identical features whose coefficients swung between and from one draw of the noise to the next, and a training that climbed to with 40 useless features while the validation fell below zero. This note changes the objective rather than the optimizer: it adds a penalty that makes large weights expensive. The penalty trades a little bias for a large reduction of variance, has a Bayesian reading as a prior, and in its L1 form selects features by setting weights exactly to zero.
Notation. As in the least-squares note, is the design matrix and the targets. Throughout this note the features are standardized (mean 0, variance 1) and the target is centred, so no intercept is needed: it is and is never penalized. is the strength of the penalty, and . is the rank of the design matrix. Its singular value decomposition is , where and have orthonormal columns and and is diagonal with the singular values (always with an index, unlike the noise level ), so the nonzero eigenvalues of are . is the soft-thresholding function.
Ridge: a penalty on the size of the weights#
Ridge regression (Hoerl and Kennard, 1970) minimizes the squared error plus the squared length of the weight vector:
The gradient is , and setting it to zero gives
The matrix has eigenvalues (and along the directions with no data), all at least . For any it is positive definite and invertible: the solution exists and is unique even with collinear features or with more features than examples, the cases where least squares broke down. Scaling matters: the penalty treats a weight of 1 on a feature measured in metres the same as on one measured in millimetres, which is why the features are standardized first, with statistics computed on the training data only.
Worked example. One feature and centred target : and . Least squares gives ; ridge with gives , half the size. Now duplicate the feature, . Least squares has infinitely many solutions, every with . Ridge has one: by symmetry , and the first equation of reads , so . The penalty splits the weight equally between identical features, the split with the smallest norm.
On the nearly identical features of the least-squares note (correlation , true weights ), three fresh draws of the noise give least-squares weights , and , and ridge with gives , and (the Code section).
Which directions it shrinks#
Substitute the SVD. Since and , the fitted values are
Least squares projects onto each principal direction of the data and keeps the projection in full. Ridge multiplies it by : directions in which the features vary a lot () are kept almost intact, directions of small variance () are shrunk almost to zero (Hastie, Tibshirani and Friedman, 2009, section 3.4.1). These are exactly the directions that made least squares unstable, because the variance of the least-squares coefficients along is . The sum of the factors, , is the trace of the ridge hat matrix and is called the effective degrees of freedom: at , falling to 0 as .
We use a newly specified synthetic sensor fixture, not observations from people or equipment. Generate 240 independent rows from eight standard-normal draws . Set , and for . The target is , with independent . The columns are sensor_a, sensor_b, control, ambient and four auxiliary signals. The redundant pair tests coefficient stability; the last four columns carry no true signal. Seed 20261113 fixes this teaching experiment. The data generator and new calculations were composed for this course with Codex assistance; no external dataset or benchmark scores are inputs.
Standardizing this fixture gives correlation between the sensor pair. The extreme eigenvalues of are and : the almost duplicated measurement creates a poorly observed direction. At , ridge keeps the largest direction with factor and the smallest with factor ; effective degrees of freedom fall from 8 to . At and they are and . These are calculated properties of this fixture, not estimates for a real sensor system.
The shrinkage introduces bias: . It can remove enough variance to make the mean squared error fall, the trade-off of the estimators note that the bias–variance note applies to every model of the course.
The Bayesian reading#
The penalty is a prior. With Gaussian noise of variance and independent priors , the negative log-posterior is the ridge objective divided by , with ; a Laplace prior gives the L1 penalty of the lasso below, with . The derivation is in the MAP section of the Bayesian inference note. Two consequences are worth stating here:
- A strong penalty is a confident prior that the weights are small; is a flat prior and gives back least squares.
- For the Gaussian prior the posterior is Gaussian, so is both its mode and its mean, and the posterior covariance gives uncertainties; the Bayesian linear regression note derives this posterior and the predictive distribution. For the Laplace prior the lasso estimate is only the mode; the posterior puts zero probability on any weight being exactly 0, so the sparsity below is a property of the optimization, not of the posterior.
The constrained form: why L1 gives zeros#
For each there is a radius such that the penalized problem has the same solution as the constrained one,
by the Lagrangian duality of convex problems (least squares under a norm constraint derives it for ridge): is the multiplier of the constraint, and a smaller corresponds to a larger . The constrained form explains the different behaviour of the two penalties.
Why the lasso zeroes weights and ridge does not
The contours of the squared error are ellipses around the least-squares solution . The constrained solution is the point of the feasible set on the lowest contour, the point where a growing ellipse first touches the set. The L2 ball is round, so the touching point is wherever the ellipse’s shape puts it, generically with all coordinates nonzero. The L1 ball is a diamond (a cross-polytope in dimensions) whose corners lie on the axes, and its corners stick out: an ellipse approaching from a wide range of directions hits a corner first, and at a corner some coordinates are exactly zero. In the figure the condition is visible as a computation: at the corner the negative gradient of the loss is , which lies strictly between the normals and of the two edges that meet there, so no move along the diamond’s boundary lowers the loss.
The lasso#
The lasso (Tibshirani, 1996) is the L1-penalized problem,
It is convex but not differentiable where a weight is zero, and it has no closed form in general. With orthonormal features, , it does. Write , the least-squares solution in that case; then , and the objective splits into one problem per coordinate, . For the derivative vanishes at , which is positive only if ; symmetrically for ; otherwise the minimum is at 0. Together:
Ridge shrinks every coefficient by the same factor; the lasso subtracts the same amount from every coefficient’s absolute value and sets those smaller than to zero.
Worked example. Orthonormal features with and . The lasso gives : two features are dropped. Ridge gives : all three are kept, smaller. scikit-learn’s Lasso minimizes , so its is in this note’s units; with that conversion it returns (the Code section).
Coordinate descent. For general , minimize over one weight at a time with the others fixed. The one-dimensional problem is the orthonormal one with replaced by the correlation of feature with the partial residual :
Cycling over the coordinates converges for the lasso (Friedman et al., 2007), and computing the solutions for a decreasing sequence of , each started from the previous one, gives the whole regularization path cheaply; this is what scikit-learn does. A related method takes a gradient step on the squared error and then soft-thresholds all coordinates (the proximal gradient method); the least angle regression algorithm computes the path exactly, because it is piecewise linear in (Efron et al., 2004).
Where the path starts. At the subgradient condition for optimality is for every . So all weights are zero for , and the first feature to enter is the one most correlated with the target. On the synthetic fixture , attained by sensor_a.
Coefficient paths of ridge and the lasso
The paths are freshly computed from the synthetic fixture. Least squares assigns standardized weights and to sensor_a and sensor_b, although their generating coefficients were equal before scaling. Ridge reduces that imbalance. Along the lasso grid the entry order is sensor_a, control, ambient, aux_1, sensor_b, aux_3, aux_2, aux_4. The model selected below retains seven coefficients, including three auxiliary signals with no true effect. Sparsity does not certify which variables caused the target.
Correlated features: the elastic net#
The lasso’s selection is unstable within a group of correlated features. When two features carry the same signal, the L1 penalty is the same for any split of the weight between them, for weights of one sign, and the squared error barely distinguishes the splits, so the lasso tends to keep one feature and drop the other, and which one depends on the noise. On two copies of one signal with correlation plus a useless feature, three draws of the data give lasso weights , and (scikit-learn’s ).
The elastic net (Zou and Hastie, 2005) adds a ridge term: . The squared term is strictly convex, so it prefers the equal split, and Theorem 1 of the paper bounds the difference between the weights of two features by a multiple of , where is their correlation: the grouping effect. The same three draws give , and (scikit-learn’s and l1_ratio=0.5), and the useless feature is still removed.
Choosing the penalty by validation#
The penalty strength is a hyperparameter, and the validation note gives the procedure: fit for a grid of on a log scale, estimate the error of each by cross-validation, keep the best, and report the final performance with a nested scheme or a test set, since the best of many cross-validated scores is optimistic. Ridge has a shortcut: its fitted values are linear in , , and the leave-one-out residual is , so leave-one-out cross-validation costs one fit per (Hastie, Tibshirani and Friedman, 2009, section 7.10.1, eq. 7.51); scikit-learn’s RidgeCV uses it.
On the synthetic fixture, use five shuffled folds (seed 17), with polynomial expansion and standardization fitted inside each training fold. Choose ridge or lasso . The table reports the mean validation and the best setting on these same folds, so these are selection scores:
| Features | Count | Least squares | Ridge, best | Lasso, best |
|---|---|---|---|---|
| original | 8 | () | () | |
| up to degree 2 | 44 | () | () | |
| up to degree 3 | 164 | () | () |
Each training fold has 192 rows. Expanding eight inputs to 164 cubic terms leaves little independent information per coefficient, and unpenalized fitting is unstable. The penalty makes the cubic fit usable, but its best score still does not beat the original linear model: the generator contains no interactions to discover. This is a controlled illustration of variance, not a recommendation to add all polynomials. A separate test set or nested validation is still required to estimate performance after selection.
Other ways of limiting a model act like penalties and appear later in the course: stopping gradient descent early (a spectral filter that, like ridge, delays fitting small-curvature directions; it is not exactly one ridge penalty for every direction), dropout and data augmentation, all in the training note, and pruning in the decision-tree note. Weight decay, shrinking every weight by a fixed fraction at each step, is the same as an L2 penalty for plain SGD; with adaptive optimizers such as Adam the two differ, and the decoupled form, AdamW, is the one used in practice (weight decay under Adam). Weight decay regularizes the fine-tuning of language models, and an L1 penalty on activations makes the sparse autoencoder sparse.
What changed#
| Least squares | Ridge | Lasso | |
|---|---|---|---|
| Objective | |||
| Solution | , if it exists | , for | no closed form; coordinate descent |
| Collinear features or | not unique, unstable | unique, weight shared | unique fit, selection unstable within groups |
| Zeros | not enforced | not enforced (only by coincidence) | exact zeros: feature selection |
| Prior | flat | Gaussian | Laplace (as MAP) |
| Hyperparameter | none | , by cross-validation | , by cross-validation |
| Bias and variance | unbiased, high variance | biased, lower variance | biased, lower variance |
Limitations#
- The penalty depends on the units. Features must be standardized, and the result changes with the scaling chosen.
- Bias. Both penalties shrink large true coefficients too; the lasso’s estimates of the features it keeps are biased towards zero, and refitting least squares on the selected features is a common remedy.
- The lasso keeps at most features when and the features are in general position, for example drawn from a continuous distribution: the solution is then unique with probability one and has at most nonzero weights (Tibshirani, 2013). With exactly duplicated columns the fit stays unique but the weights do not: any split of a weight between two copies, with the same sign, has the same fit and penalty. Within strongly correlated groups the choice is arbitrary; the elastic net softens both limits.
- Selection is not inference. A feature dropped by the lasso may still matter, and standard errors computed after selection are too small.
- One more hyperparameter. costs a cross-validation loop and makes an honest error estimate need a nested one.
What you should remember#
- Ridge: , unique for every ; it shrinks each principal direction by , the small-variance directions most; .
- The penalties are priors: Gaussian gives ridge with , Laplace gives the lasso as a MAP estimate.
- The L1 ball has corners on the axes, so the lasso sets weights exactly to zero; with orthonormal features it soft-thresholds the least-squares coefficients at , while ridge divides them by .
- All lasso weights are zero for ; the path is computed by coordinate descent with warm starts.
- The elastic net adds an L2 term so that correlated features share their weight.
- Standardize features, do not penalize the intercept, choose by cross-validation and report with nested cross-validation.
Code#
The worked examples, the new fixture, spectral shrinkage, the lasso path and the polynomial comparison. Recomputed with NumPy 2.5.4 and scikit-learn 1.9.1; the recorded run raised no convergence warnings. No external data is downloaded:
import numpy as np, warnings
from sklearn.linear_model import Ridge, Lasso, ElasticNet, LinearRegression, lasso_path
from sklearn.model_selection import KFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
warnings.filterwarnings('ignore', category=FutureWarning) # only scikit-learn 1.9's notice about n_alphas; convergence warnings stay on
rng = np.random.default_rng(0)
ridge = lambda X, y, lam: np.linalg.solve(X.T @ X + lam * np.eye(X.shape[1]), X.T @ y)
# worked example: x = (-1, 0, 1), centred y = (-2, 0, 2); then the same feature twice
x = np.array([[-1.], [0], [1]]); y = np.array([-2., 0, 2])
print(ridge(x, y, 1e-12), ridge(x, y, 2.0), ridge(np.hstack([x, x]), y, 2.0).round(3)) # [2.] [1.] [0.667 0.667]
# orthonormal features: the lasso soft-thresholds z = X^T y at lambda/2, ridge divides it by 1 + lambda
n = 50
Xo = np.linalg.qr(rng.normal(size=(n, 3)))[0] # orthonormal columns
z = np.array([3.0, 1.0, -0.5]); yo = Xo @ z
lam = 2.0 # objective |y - Xw|^2 + lam |w|_1; scikit-learn's alpha = lam / (2n)
print(Lasso(alpha=lam / (2 * n), fit_intercept=False, tol=1e-12).fit(Xo, yo).coef_.round(3) + 0, ridge(Xo, yo, lam).round(3))
# [2. 0. 0.] [ 1. 0.333 -0.167]
# two nearly identical features (the least-squares note's example): ridge with lambda = 1 is stable
x1 = rng.normal(size=100); X2 = np.column_stack([x1, x1 + 0.01 * rng.normal(size=100)])
for _ in range(3):
t = X2.sum(1) + rng.normal(size=100)
print(np.linalg.lstsq(X2, t, rcond=None)[0].round(2), ridge(X2, t, 1.0).round(2))
# [ 4.81 -2.86] [0.99 0.95] | [-15.84 17.95] [0.97 1.13] | [-0.11 2.09] [0.98 0.99]
# New synthetic fixture; standardize and center for the full-data path only.
def make_data():
# Independent dimensionless simulated inputs, with one deliberately redundant pair.
rng = np.random.default_rng(20261113)
base = rng.normal(size=(240, 8))
X = base.copy()
X[:, 1] = base[:, 0] + 0.08 * base[:, 1]
y = 20 + X @ np.array([4., 4., -3., 2., 0., 0., 0., 0.])
y += 4 * rng.normal(size=len(X))
return X, y
X, yd = make_data()
names = ['sensor_a', 'sensor_b', 'control', 'ambient', 'aux_1', 'aux_2', 'aux_3', 'aux_4']
Xs = (X - X.mean(0)) / X.std(0); yc = yd - yd.mean()
assert np.max(abs(ridge(Xs, yc, 10) - Ridge(alpha=10).fit(Xs, yc).coef_)) < 1e-9
d2 = np.linalg.eigvalsh(Xs.T @ Xs)[::-1]
print(d2.round(3))
for lam in (1, 10, 100, 1000):
factors = d2 / (d2 + lam)
print(lam, factors[[0, -1]].round(3), round(factors.sum(), 2))
# lambda=10: [0.980, 0.079], df=6.81; lambda=100: df=5.04; lambda=1000: df=1.48
print(round(2 * abs(Xs.T @ yc).max(), 2), names[abs(Xs.T @ yc).argmax()]) # 3890.52 sensor_a
alphas, coefs, _ = lasso_path(Xs, yc, n_alphas=2000, eps=1e-5, max_iter=200000, tol=1e-9)
order = []
for column in coefs.T:
order += [names[j] for j in np.flatnonzero(abs(column) > 1e-9) if names[j] not in order]
print(order)
# ['sensor_a', 'control', 'ambient', 'aux_1', 'sensor_b', 'aux_3', 'aux_2', 'aux_4']
# Selection scores, with every transformation inside each training fold.
cv = KFold(5, shuffle=True, random_state=17)
for deg in (1, 2, 3):
pipe = lambda model: make_pipeline(PolynomialFeatures(deg, include_bias=False), StandardScaler(), model)
score = lambda model: float(cross_val_score(pipe(model), X, yd, cv=cv, scoring='r2').mean())
p = PolynomialFeatures(deg, include_bias=False).fit(X).n_output_features_
r = {a: score(Ridge(alpha=a)) for a in (0.1, 1, 10, 100, 1000)}
l = {a: score(Lasso(alpha=a, max_iter=200000, tol=1e-6)) for a in (0.03, 0.1, 0.3, 1, 3)}
print(deg, p, round(score(LinearRegression()), 3), max(r, key=r.get), round(max(r.values()), 3), max(l, key=l.get), round(max(l.values()), 3))
# 1 8 0.812 1 0.812 0.1 0.814 | 2 44 0.770 10 0.787 0.3 0.809 | 3 164 -7.090 100 0.652 0.3 0.803
# two copies of one signal (correlation 0.999) and a useless feature, three draws: the lasso picks a copy, the elastic net shares
for seed in (0, 1, 2):
r = np.random.default_rng(seed); zz = r.normal(size=200)
Xe = np.column_stack([zz + 0.03 * r.normal(size=200), zz + 0.03 * r.normal(size=200), r.normal(size=200)])
Xe = (Xe - Xe.mean(0)) / Xe.std(0); ye = 2 * zz + r.normal(size=200); ye -= ye.mean()
print(Lasso(alpha=0.5).fit(Xe, ye).coef_.round(2) + 0, ElasticNet(alpha=0.5, l1_ratio=0.5).fit(Xe, ye).coef_.round(2) + 0)
# [1.46 0. 0. ] [0.76 0.76 0. ] | [0. 1.4 0. ] [0.72 0.74 0. ] | [0.6 0.76 0. ] [0.71 0.72 0. ]
Next#
The linear regression section ends with a model that predicts a number, is fitted by formula or by descent, and does not chase the noise. Many targets are not numbers but classes: spam or not, default or repayment. The next note asks what a linear model should minimize when the answer is a side of a hyperplane, why squared error is the wrong loss for that, and which losses replace it. The ridge penalty comes along: it is the second term of the support vector machine objective and the heart of kernel ridge regression.
References#
- E. Sokolov et al. Машинное обучение (HSE), lecture notes, lecture 4: regularization, hyperparameters, sparse models and the proximal step, feature transformations.
- A. E. Hoerl, R. W. Kennard. Ridge regression: biased estimation for nonorthogonal problems. Technometrics, 12(1), 1970.
- R. Tibshirani. Regression shrinkage and selection via the lasso. Journal of the Royal Statistical Society B, 58(1), 1996.
- H. Zou, T. Hastie. Regularization and variable selection via the elastic net. Journal of the Royal Statistical Society B, 67(2), 2005. Section 2.3, Theorem 1 (the grouping effect).
- B. Efron, T. Hastie, I. Johnstone, R. Tibshirani. Least angle regression. Annals of Statistics, 32(2), 2004.
- J. Friedman, T. Hastie, H. Höfling, R. Tibshirani. Pathwise coordinate optimization. Annals of Applied Statistics, 1(2), 2007.
- R. J. Tibshirani. The lasso problem and uniqueness. Electronic Journal of Statistics, 7, 2013. Uniqueness for features from a continuous distribution and the bound of nonzero weights.
- T. Hastie, R. Tibshirani, J. Friedman. The Elements of Statistical Learning, 2nd ed. Springer, 2009. Section 3.4.1 (ridge regression, the SVD view and effective degrees of freedom), Section 3.4.2 (the lasso), Section 3.4.3 (the constraint regions and soft thresholding), Section 3.8.6 (pathwise coordinate optimization), Section 7.10.1 (cross-validation and the leave-one-out shortcut).
- C. M. Bishop. Pattern Recognition and Machine Learning. Springer, 2006. Section 3.1.4 (regularized least squares), Section 3.3 (Bayesian linear regression).