Skip to main content
MahiDev — Learn. Build. Become AI-ready.

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
Elastic Net MahiDev

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

python
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:

text
[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_ratio near 1 behaves like Lasso. Near 0 it behaves like Ridge.
  • Standardize inputs first so the penalty treats them on the same scale.

Loading playground…