Sub topic 15
Ridge, Lasso and ElasticNet
This chapter assumes you can fit a LinearRegression, build a Pipeline with StandardScaler, and read cross-validated scores. It also assumes you know why plain least squares overfits when features are many or correlated.
The idea: penalize large coefficients
Ordinary least squares minimizes only the squared error. Regularized models add a penalty on the size of the coefficients. The penalty trades a little bias for lower variance, so coefficients stop swinging wildly when features are correlated or data is scarce. The strength of the penalty is set by alpha. A larger alpha gives smaller coefficients, and alpha=0 is close to plain OLS.
| Model | Penalty | Effect on coefficients |
|---|---|---|
| `Ridge` | sum of squared coefficients (L2) | Shrinks all of them toward zero, rarely to exactly zero |
| `Lasso` | sum of absolute coefficients (L1) | Shrinks and sets some exactly to zero, so it selects features |
| `ElasticNet` | mix of L1 and L2, set by `l1_ratio` | Selects features but keeps correlated ones together |
The intercept is not penalized.
Comparing the three
Because the penalty depends on coefficient size, features must be on the same scale. Putting StandardScaler in a pipeline handles this and keeps the scaler fitted on training data only.
from sklearn.datasets import load_diabetes
from sklearn.linear_model import ElasticNet, Lasso, Ridge
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_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
)
models = {
"ridge": Ridge(alpha=1.0),
"lasso": Lasso(alpha=1.0),
"enet": ElasticNet(alpha=1.0, l1_ratio=0.5),
}
for name, reg in models.items():
pipe = make_pipeline(StandardScaler(), reg).fit(X_train, y_train)
coefs = pipe[-1].coef_
print(
name,
"test R2:", round(pipe.score(X_test, y_test), 3),
"zero coefs:", int((coefs == 0).sum()),
)The "zero coefs" count shows the difference. Ridge keeps every feature. Lasso and ElasticNet may drop some. The exact counts depend on alpha.
Choosing between them
Among a group of correlated features, Lasso tends to keep one and zero the others. Which one it keeps can change with small changes in the data. ElasticNet spreads weight across the group, which is more stable.
Common errors
- Forgetting to scale. A feature measured in large units gets a small coefficient and is barely penalized. A feature in small units is penalized heavily. The result depends on units, not on usefulness.
- Scaling outside the pipeline. Fitting the scaler on all data before splitting leaks test information into training.
- Reusing the default
alpha. The default of 1.0 is arbitrary for your data. Tune it withRidgeCV,LassoCV, orGridSearchCV, which later chapters cover. - Too large an
alphawith Lasso. All coefficients become zero and the model predicts the training mean. - Reading Lasso's zeros as proof of irrelevance. A zero only means the feature was not needed at that
alpha, given the others.
Exercise
You fit a Lasso model on unscaled features. One feature is a price in dollars, in the tens of thousands. The others are fractions between 0 and 1. What is likely to happen to the price coefficient, and how do you fix it?
Show answer
The price feature needs only a tiny coefficient to have a large effect, so the L1 penalty barely touches it, while the small-unit features are penalized heavily and may be zeroed out. Fix it by putting StandardScaler before Lasso in a pipeline, so all features are penalized on the same scale.