Lesson 21
Elastic Net
Combine the Ridge and Lasso penalties so related inputs can stay in the model while weak ones still drop. One example is on this page.
Intermediate12 min
What You Will Learn
- Idea
- Example
- When to use it
Idea
Elastic net mixes an L1 penalty and an L2 penalty. L1 can zero out noise. L2 stops the model from picking only one input when several inputs tell the same story. l1_ratio sets how much of the mix is Lasso.
Example
import numpy as np
from sklearn.linear_model import ElasticNet
X = np.array([[1, 1.1], [2, 2.1], [3, 2.8], [4, 4.2]], dtype=float)
y = np.array([2, 4, 6, 8], dtype=float)
coef = ElasticNet(alpha=0.1, l1_ratio=0.5).fit(X, y).coef_
print(np.round(coef, 2).tolist())Output:
[1.13, 0.78]When to use it
- Use it when correlated inputs should stay together and a pure Lasso fit would drop one of them.
l1_rationear 1 behaves like Lasso. Near 0 it behaves like Ridge.- Standardize inputs first so the penalty treats them on the same scale.
Loading playground…