Sub topic 15
Ridge, Lasso and ElasticNet
This chapter assumes you can fit a LinearRegression, build a Pipeline, and run cross_val_score. You should also know why scaling matters and how overfitting and correlated features make ordinary least squares (OLS) coefficients unstable. Here you will see how three penalized variants control that instability and how to choose between them.
The idea: add a penalty to the loss
OLS picks coefficients that minimize squared error on the training data. With many features, or features that move together, OLS can reach a low training error with large coefficients that cancel each other out. Those coefficients fit noise and change a lot between samples.
Regularization adds a penalty on coefficient size to the loss. The model then trades a little training error for smaller, steadier coefficients. This adds a small amount of bias and removes a larger amount of variance.
scikit-learn defines the objectives like this, where n is the number of samples and w is the coefficient vector:
| Model | Minimizes | Column | Column | Column | Column | Column | Column | Column | Column | Column | Column | Column | Column |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| `Ridge` | ` | y - Xw | ² + alpha * | w | ₂²` | ||||||||
| `Lasso` | `(1 / 2n) * | y - Xw | ² + alpha * | w | ₁` | ||||||||
| `ElasticNet` | `(1 / 2n) * | y - Xw | ² + alpha * l1_ratio * | w | ₁ + 0.5 * alpha * (1 - l1_ratio) * | w | ₂²` |
Three details matter in practice:
- The intercept is never penalized.
Ridgedoes not divide the squared error byn, butLassoandElasticNetdo. The samealphatherefore does not mean the same strength across the models, and you can't carry a value from one model to another.alpha=0removes the penalty and gives plain OLS. UseLinearRegressionfor that. The coordinate descent solver behindLassoandElasticNetwarns against tiny alphas.
What each penalty does
Ridge uses the L2 penalty, the sum of squared coefficients. It shrinks every coefficient toward zero, but it rarely makes one exactly zero. Among correlated features it tends to share the weight between them.
Lasso uses the L1 penalty, the sum of absolute values. It can set coefficients exactly to zero, so it selects features as a side effect. When several features are strongly correlated, Lasso tends to keep one and drop the others, and which one it keeps can change with small changes in the data.
ElasticNet mixes both penalties. l1_ratio=1.0 is Lasso, and values near 0 behave like Ridge. It keeps some of Lasso's sparsity and is steadier with correlated groups.
Always scale first
The penalty is applied to the raw coefficient values. A feature measured in small units needs a large coefficient, so the penalty hits it harder than a feature measured in large units. Without scaling, the penalty depends on units instead of usefulness. Put StandardScaler in the pipeline before any penalized model. Because the scaler is inside the pipeline, cross-validation refits it on each training fold, which avoids leakage.
Comparing the three on one dataset
The diabetes dataset has 10 numeric features. The code below scores each model with 5-fold cross-validation, then fits each on the full data to inspect the coefficients.
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import ElasticNet, Lasso, LinearRegression, Ridge
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_diabetes(return_X_y=True)
models = {
"ols": LinearRegression(),
"ridge": Ridge(alpha=1.0),
"lasso": Lasso(alpha=1.0),
"enet": ElasticNet(alpha=1.0, l1_ratio=0.5),
}
for name, est in models.items():
pipe = make_pipeline(StandardScaler(), est)
scores = cross_val_score(pipe, X, y, cv=5, scoring="r2")
pipe.fit(X, y)
coef = pipe[-1].coef_
print(
f"{name:6s} cv R2 = {scores.mean():.3f} "
f"zero coefs = {int(np.sum(coef == 0))} "
f"max |coef| = {np.abs(coef).max():.1f}"
)Expect the zero coefs count to be 0 for OLS and Ridge and above 0 for Lasso at this alpha. Exact numbers depend on your scikit-learn version, so read the output instead of assuming it. The cross-validated R² of the penalized models may not beat OLS here. This dataset has few features and plenty of rows, so the penalty has little variance to remove.
Correlated features: Lasso versus ElasticNet
The next example builds three near-duplicate features that all carry the same signal, plus two noise features. It then compares how Lasso and ElasticNet spread the weight.
import numpy as np
from sklearn.linear_model import ElasticNet, Lasso
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
base = rng.normal(size=(200, 1))
copies = [base + 0.05 * rng.normal(size=(200, 1)) for _ in range(3)]
noise = rng.normal(size=(200, 2))
X = np.hstack(copies + [noise])
y = 3.0 * base[:, 0] + rng.normal(0, 0.5, size=200)
lasso = make_pipeline(StandardScaler(), Lasso(alpha=0.1)).fit(X, y)
enet = make_pipeline(
StandardScaler(), ElasticNet(alpha=0.1, l1_ratio=0.5)
).fit(X, y)
print("lasso:", np.round(lasso[-1].coef_, 2))
print("enet: ", np.round(enet[-1].coef_, 2))Lasso usually puts most of the weight on one of the first three columns and zeros the others. ElasticNet usually gives all three similar, non-zero weights. If you refit with a different seed, the column Lasso picks can change. That instability is the reason to prefer ElasticNet when you need to interpret grouped features.
Choosing alpha and l1_ratio
alpha and l1_ratio are hyperparameters, so choose them by cross-validation on training data, never by looking at the test set. scikit-learn has built-in versions that search along a path of alphas efficiently:
RidgeCV(alphas=...)LassoCV(cv=5)ElasticNetCV(l1_ratio=[0.1, 0.5, 0.9, 1.0], cv=5)
GridSearchCV also works with a pipeline. Prefix each parameter with the step name and two underscores:
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import ElasticNet
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0
)
pipe = Pipeline([
("scale", StandardScaler()),
("model", ElasticNet(max_iter=10000)),
])
grid = {
"model__alpha": np.logspace(-3, 1, 9),
"model__l1_ratio": [0.1, 0.5, 0.9],
}
search = GridSearchCV(pipe, grid, cv=5, scoring="neg_root_mean_squared_error")
search.fit(X_train, y_train)
print("best params:", search.best_params_)
print("test R2:", search.score(X_test, y_test))Note that with scoring="neg_root_mean_squared_error", search.score returns the negative RMSE, not R². The label above is misleading, so print it as test neg RMSE or compute R² with r2_score on search.predict(X_test).
Common errors
- Skipping the scaler, which makes the penalty depend on feature units.
- Comparing alphas across models. Ridge's
alpha=1and Lasso'salpha=1are different penalties. - Ignoring
ConvergenceWarningfrom Lasso or ElasticNet. Raisemax_iter, or scale the features, before trusting the coefficients. - Searching alphas on a linear grid. Alpha acts on a log scale, so use
np.logspace. - Reading shrunken coefficients as unbiased effects. Penalized coefficients are deliberately biased toward zero.
- Evaluating on the test set during tuning. Tune with cross-validation on the training split, then score once on the test set.
Exercise
You fit Lasso on unscaled features, where one feature is a price in dollars (values around 100000) and another is a ratio between 0 and 1. Lasso drops the ratio feature. Why might this be misleading, and what is the fix?
Show answer
The ratio needs a very large coefficient to have the same effect as the price feature, so the L1 penalty punishes it far more and pushes it to zero because of its units, not its usefulness. Put StandardScaler before Lasso in a pipeline, so all features are on a comparable scale, then tune alpha with cross-validation and check again.