Regularization: Ridge & Lasso
An overfitting linear model usually has a recognisable symptom: huge coefficients that cancel each other out to thread the line through noisy points. Regularization adds a penalty for large coefficients to the training objective, so the model has to balance "fit the data" against "keep the coefficients small".
ordinary least squares: minimise error
ridge (L2): minimise error + alpha * sum(coef²)
lasso (L1): minimise error + alpha * sum(|coef|)alpha controls the strength: 0 means no penalty (plain linear regression); larger values push coefficients towards zero.
Huge coefficients in an overfit model
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression, Ridge
rng = np.random.default_rng(0)
x = rng.uniform(0, 1, 20).reshape(-1, 1)
y = np.sin(2 * np.pi * x).ravel() + rng.normal(0, 0.2, 20)
for name, reg in [("plain", LinearRegression()), ("ridge", Ridge(alpha=0.1))]:
model = make_pipeline(PolynomialFeatures(10, include_bias=False), StandardScaler(), reg).fit(x, y)
coefs = model[-1].coef_
print(f"{name}: largest |coef| = {np.abs(coefs).max():10.1f}")plain: largest |coef| = 95592.2
ridge: largest |coef| = 1.7
The unregularized degree-10 model needs enormous coefficients; ridge keeps them small.
Ridge regression in action
Let's compare errors for several alpha values on the same flexible degree-12 polynomial model, trained on 30 noisy points and tested on 500 fresh ones:
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error
rng = np.random.default_rng(0)
x = rng.uniform(0, 1, 30).reshape(-1, 1)
y = np.sin(2 * np.pi * x).ravel() + rng.normal(0, 0.3, 30)
x_test = rng.uniform(0, 1, 500).reshape(-1, 1)
y_test = np.sin(2 * np.pi * x_test).ravel() + rng.normal(0, 0.3, 500)
print("alpha train MSE test MSE")
for alpha in [1e-8, 1e-4, 1e-2, 0.1, 1, 10]:
model = make_pipeline(PolynomialFeatures(12), StandardScaler(), Ridge(alpha=alpha)).fit(x, y)
tr = mean_squared_error(y, model.predict(x))
te = mean_squared_error(y_test, model.predict(x_test))
print(f"{alpha:<9g} {tr:9.3f} {te:8.3f}")alpha train MSE test MSE
1e-08 0.040 0.137
0.0001 0.042 0.131
0.01 0.058 0.115
0.1 0.088 0.099
1 0.187 0.152
10 0.242 0.216
Too little regularization overfits (low training error, higher test error); too much makes the model too stiff (both errors rise). In between is a sweet spot — find it with cross validation, for example with RidgeCV.
Note: Always scale features before regularizing. The penalty treats all coefficients equally, so a feature measured in large units would be penalised unfairly little.
Lasso: shrinking to exactly zero
Lasso's absolute-value penalty has a special property: it drives some coefficients to exactly zero, effectively removing those features. That makes Lasso a built-in feature selector. Here only 3 of 10 features actually affect the target:
import numpy as np
from sklearn.linear_model import LinearRegression, Lasso, Ridge
rng = np.random.default_rng(1)
X = rng.normal(size=(100, 10))
y = 4 * X[:, 0] - 3 * X[:, 3] + 2 * X[:, 7] + rng.normal(0, 1, 100)
print("linear:", LinearRegression().fit(X, y).coef_.round(2))
print("ridge: ", Ridge(alpha=10).fit(X, y).coef_.round(2))
print("lasso: ", Lasso(alpha=0.2).fit(X, y).coef_.round(2))linear: [ 4.08 0.06 -0.07 -2.89 0. -0.09 -0.12 1.99 -0.03 0.17]
ridge: [ 3.72 -0.04 -0.1 -2.63 0.01 -0.07 -0.16 1.89 -0.08 0.14]
lasso: [ 3.92 0. -0. -2.7 0. -0. -0. 1.84 -0. 0. ]
Plain regression gives every feature a small non-zero weight from noise. Ridge shrinks them all a bit. Lasso keeps features 0, 3 and 7 and sets most of the rest to exactly 0.
How strong should Lasso be?
On the diabetes data, increasing alpha makes Lasso drop more and more features. Cross validation shows what that costs in accuracy (R²):
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Lasso
from sklearn.model_selection import cross_val_score
X, y = load_diabetes(return_X_y=True)
names = ["age", "sex", "bmi", "bp", "s1", "s2", "s3", "s4", "s5", "s6"]
for alpha in [0.01, 0.1, 0.3, 1]:
model = Lasso(alpha=alpha, max_iter=10000)
kept = [n for n, c in zip(names, model.fit(X, y).coef_) if c != 0]
r2 = cross_val_score(model, X, y, cv=5).mean()
print(f"alpha={alpha:<5} CV R^2={r2:.3f} kept {len(kept):2}: {kept}")alpha=0.01 CV R^2=0.481 kept 10: ['age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6']
alpha=0.1 CV R^2=0.480 kept 7: ['sex', 'bmi', 'bp', 's1', 's3', 's5', 's6']
alpha=0.3 CV R^2=0.458 kept 4: ['bmi', 'bp', 's3', 's5']
alpha=1 CV R^2=0.338 kept 3: ['bmi', 'bp', 's5']
With alpha=0.1 Lasso throws away three features at no cost in accuracy; at alpha=0.3 it keeps only four and loses a little; at alpha=1 it has become too simple. To search automatically, use RidgeCV(alphas=[...]) or LassoCV(cv=5), which try a list of alphas with built-in cross validation and store the winner in alpha_.
Regularization elsewhere
Regularization isn't only for linear regression:
| Model | Regularization knob |
|---|---|
Ridge, Lasso, ElasticNet |
alpha (bigger = stronger) |
LogisticRegression, SVC |
C (bigger = weaker; C = 1/alpha) |
MLPClassifier |
alpha (L2 penalty on weights) |
| Decision trees | max_depth, min_samples_leaf (limit complexity) |
ElasticNet mixes both penalties (l1_ratio sets the mix) and is a good choice when many features are correlated.
Go further: Ridge, Lasso and Elastic Net implements the three penalties from scratch and chooses
alphaby cross-validation.
Test yourself
What does increasing alpha in Ridge do?
- Makes coefficients larger
- Pushes coefficients towards zero (stronger regularization)
- Adds more features
- Removes the intercept
Which regularizer can set coefficients to exactly zero?
- Ridge (L2)
- Lasso (L1)
- Neither
- Both equally
In LogisticRegression, how do you make regularization stronger?
- Increase C
- Decrease C
- Increase max_iter
- Set fit_intercept=False