Elastic Net
Quick answer
Elastic Net combines absolute-weight and squared-weight penalties. It is useful when sparse solutions are desirable but correlated predictors make pure Lasso selection unstable. The combination is a modeling option, not an automatic improvement. Examples are standalone local Python 3.13.5 snippets; library examples use scikit-learn 1.8.0. ByteMind execution is unverified.
Calculate the two penalty contributions
w = [2,-3]a,r = 2,0.25l1 = a*r*sum(abs(x) for x in w)l2 = 0.5*a*(1-r)*sum(x*x for x in w)print(l1,l2,l1+l2)Expected output:
2.5 9.75 12.25L1 and L2 contribute separately; the squared penalty includes a factor of one half.
How it works
For n rows, alpha >= 0 and ratio r between 0 and 1, the objective is SSE/(2n) + alpharL1 + 0.5alpha*(1-r)L2². At r=1 it reduces to the Lasso objective; at r=0 it has a ridge-like objective with a different scale (Ridge alpha=nElasticNet alpha under these conventions). Use dedicated Ridge at the pure L2 endpoint and LinearRegression for unpenalized fitting. For a centered normalized orthogonal feature, w=soft(z,alphar)/(1+alpha(1-r)), where z=mean(x*y). The numerator can be zero and the denominator shrinks surviving weights. Positive L2 contribution makes the objective strictly convex in weights, encouraging correlated columns to share influence, though not guaranteeing equal coefficients except in symmetric cases. Tune alpha and ratio together using a fixed validation split or CV; for each fit, learn scaling from its training fold. Report validation error and a coefficient stability diagnostic. A low error and stable coefficients do not establish causal interpretation.
Fit a symmetric correlated design
from sklearn.linear_model import ElasticNetX = [[-1,-1],[1,1]]y = [-3,3]m = ElasticNet(alpha=1,l1_ratio=.5,fit_intercept=False,tol=1e-12,max_iter=10000).fit(X,y)print(m.coef_.round(5).tolist())Expected output:
[1.0, 1.0]The duplicate columns are symmetric, and the positive L2 term yields equal unique weights in this fixture.
Common mistakes
Do not call a ratio of 0.5 an equal contribution to the final objective: absolute and squared norms have different magnitudes. Do not choose ratio by looking at the test score.
Practice and next steps
With normalized independent feature z=3, alpha=2 and ratio=0.5, compute the coefficient using soft thresholding and the shrinkage denominator. Explain both effects. Complete the knowledge check and coding exercise. Next: Polynomial basis and overfitting.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Elastic Net — knowledge check
Apply elastic net to new examples.
What happens at l1_ratio=1?
At alpha=2, ratio=0.5 and z=3 for a normalized orthogonal coordinate, what is w?
What should determine alpha and ratio?
Why may Elastic Net share weights between identical columns?
Does ratio=0.5 imply equal numeric penalty contributions?