Week 06 · Ridge, lasso, and elastic net
Inspect how each penalty treats strongly correlated features.
← Week 5 · Subject contents · Week 7 →
Inspect how each penalty treats strongly correlated features.
Work through the problem
For standardized inputs, the scikit-learn ElasticNet objective is RSS/(2n) + αrΣ|wⱼ| + α(1−r)Σwⱼ²/2. The L1 term has a corner at zero and can set coefficients exactly to zero. The L2 term spreads weight across correlated predictors. Ridge in the lab uses RSS + λΣwⱼ², so λ = nα gives the comparable pure L2 scaling.
If two columns were identical and their combined coefficient were 2, assigning weights (1,1) costs 2 under the sum of squares, versus 4 at (2,0). Both assignments cost 2 under the sum of absolute values. Scaling a column changes the coefficient needed for the same prediction, so put scaling inside a training pipeline.
Penalties shrink correlated predictors.
Run the Python lab
import numpy as np
from sklearn.linear_model import Ridge, Lasso, ElasticNet
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(44)
a = rng.normal(size=80)
X = StandardScaler().fit_transform(np.c_[a,a+rng.normal(0,.15,80),rng.normal(size=80)])
y = 2*a+rng.normal(0,.2,80)
strengths = [.02,.1,.4,1.0]
paths = {}
for a in strengths:
fits = {"Ridge": Ridge(alpha=len(y)*a), "Lasso": Lasso(alpha=a), "Elastic net": ElasticNet(alpha=a,l1_ratio=.5)}
for name, model in fits.items():
w = model.fit(X,y).coef_
paths.setdefault(name,[]).append(np.linalg.norm(w,1))
print(a,name,w.round(2))
assert paths["Ridge"][-1] < paths["Ridge"][0]
Output from the lab
0.02 Ridge [ 1.22 0.56 -0.07]
0.02 Lasso [ 1.61 0.17 -0.04]
0.02 Elastic net [ 1.35 0.44 -0.06]
0.1 Ridge [ 0.96 0.75 -0.08]
0.1 Lasso [ 1.6 0.12 -0. ]
0.1 Elastic net [ 1.05 0.67 -0.03]
0.4 Ridge [ 0.78 0.72 -0.1 ]
0.4 Lasso [ 1.41 0. -0. ]
0.4 Elastic net [ 0.79 0.68 -0. ]
1.0 Ridge [ 0.61 0.59 -0.1 ]
1.0 Lasso [ 0.81 0. -0. ]
1.0 Elastic net [ 0.55 0.5 -0. ]
Practice
- Why may a sparse fit switch between two features across samples?
Check your reasoning
- If the features carry nearly the same signal, small sample changes can make either one marginally preferable.