smartyfy.mrindigi.com

AI & Machine Learning Master Course — 046. Lasso and elastic net

Smartyfy AI & Machine Learning Master Course

Course ID: smartyfy-ai-ml-master-200

Lesson 046: Lasso and elastic net

Prerequisites: Lesson 045. Learning outcome: Compare sparse and combined penalties under correlated features.

1. Shrinkage and sparsity answer different needs

Ridge shrinks coefficient magnitude but usually keeps every coefficient nonzero. Sometimes a smaller set of predictive inputs is useful for acquisition cost, interpretation, or storage. Lasso adds an absolute-value penalty that can make some fitted coefficients exactly zero. This sparsity is a property of an optimization solution, not proof that the omitted inputs are irrelevant in the world.

Consider two nearly interchangeable parcel measurements. Either can help predict the target. A sparse method may retain one and discard the other because keeping both offers little extra fit under its penalty. A small change in data can switch the selected measurement. The resulting compact model can predict adequately while its feature-selection story is unstable.

2. Understand the objective and the corner at zero

Scikit-learn Lasso minimizes residual sum of squares divided by 2n, plus α times the sum of absolute coefficients. The intercept is handled separately without the usual coefficient penalty. This normalization differs from the Ridge objective in the previous lesson, so matching numerical α values does not mean matching penalty strengths.

For a centered single feature with average x² equal to one, define z as the average xy. The lasso coefficient is sign(z) times max(|z|−α,0). This soft-threshold rule first shrinks the magnitude and then sets it to zero if it falls below the threshold. It is exact for this one-feature normalization, not a formula for independently shrinking every coefficient in a correlated multifeature problem.

In the first example, x alternates between −1 and 1 and y=2x, giving z=2. At α=0.5, the coefficient is 1.5. At α=2 or 3, it is zero. The absolute-value penalty has a corner at zero, which makes such exact zero solutions possible. Ridge's smooth quadratic penalty behaves differently.

A one-feature lasso curve w = max(2 − α, 0) passes through (0.5, 1.5), reaches zero at α = 2 and remains zero at 3. A separate grouped chart shows fitted standardized coefficients: lasso approximately 2.6532, 0.2085, 0; elastic net 1.5272, 1.3135, 0. These are labelled sample-specific allocations.
Lasso can set a coefficient exactly to zero. The added squared penalty in elastic net can share a predictive role across correlated inputs, as this particular sample illustrates. Open full-size diagram

3. Elastic net combines two preferences

Elastic net combines an absolute penalty and a squared penalty. In scikit-learn its objective is squared error divided by 2n, plus αr times the absolute coefficient sum, plus α(1−r)/2 times the squared coefficient sum. The l1_ratio parameter is r. At r=1 the objective matches lasso; intermediate values retain both kinds of shrinkage.

The squared part can encourage more stable sharing among strongly correlated inputs, while the absolute part can preserve sparsity. This is a tendency under the model and data, not a guarantee that every related feature is selected together. At the pure squared-penalty endpoint, a dedicated Ridge solver is usually preferable, with the normalization conversion explicitly accounted for.

Choose α and the mixture using development validation of the complete pipeline. Standardize continuous features within each training fold so numerical units do not accidentally determine the penalty. If feature measurement costs are the motivation, evaluate those costs directly; sparse coefficients alone do not tell you whether collecting a discarded feature can actually stop.

4. Check optimization and selection stability

Coordinate-descent solvers iterate toward the solution. A convergence warning means the requested numerical criterion was not reached; do not hide it and present coefficients as a finished fit. Inspect scaling, tolerance, iteration limits, and penalty strength. Correlated features can make convergence and interpretation harder even when the dataset is small.

Repeat development analyses across sensible resamples or folds to examine which features survive. A feature selected in only a few fits may not support a strong substantive claim. Classical unadjusted significance tests applied after selection can also be misleading because the same outcomes influenced the choice of variables. Predictive sparsity and confirmatory inference require different evidence.

CPU lab: exact thresholding and correlated predictors

The CPU script uses NumPy and scikit-learn, checked with versions 2.3.5 and 1.8.0. The first assertions verify the one-feature soft-threshold calculation. The second experiment creates two correlated synthetic measurements plus an unrelated candidate, then fits prespecified lasso and elastic-net pipelines without claiming held-out performance.

Lasso coefficients are approximately[2.6532, 0.2085, 0], whereas elastic net gives[1.5272, 1.3135, 0] in the standardized representation. Both retain zero for the third feature in this particular sample. Elastic net shares the signal more evenly here, but those exact allocations are not stable truths about feature importance. The iteration limit is deliberately generous, and the final run completed without a convergence warning.

import numpy as np
from sklearn.linear_model import Lasso, ElasticNet
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
x=np.array([-1.,1.,-1.,1.])[:,None];y=2*x[:,0]
for alpha in [.5,2.,3.]:
    model=Lasso(alpha=alpha,fit_intercept=False,tol=1e-10).fit(x,y)
    expected=max(2-alpha,0)
    assert np.isclose(model.coef_[0],expected)
    print('alpha/coefficient:',alpha,model.coef_[0])
rng=np.random.default_rng(46)
a=rng.normal(size=80);X=np.column_stack([a,a+.1*rng.normal(size=80),rng.normal(size=80)])
y=3*a+.1*rng.normal(size=80)
for estimator in [Lasso(alpha=.1,max_iter=100000,tol=1e-8),
                  ElasticNet(alpha=.1,l1_ratio=.5,max_iter=100000,tol=1e-8)]:
    pipe=make_pipeline(StandardScaler(),estimator).fit(X,y)
    print(type(estimator).__name__,estimator.coef_.round(4).tolist())

Four practice questions with worked answers

Practice 1

For standardized one-feature z=−1.2 and α=0.5, calculate the lasso coefficient.

Answer: Take the magnitude 1.2, subtract 0.5 to get 0.7, then restore the negative sign. The coefficient is −0.7. If α were 1.5, the maximum with zero would set the coefficient to zero. This calculation assumes the stated one-feature scaling and objective.

Practice 2

Why can two almost-identical inputs make a sparse feature list unstable?

Answer: They carry overlapping predictive information. Small sample changes can make either slightly more useful under the penalty, so the optimizer may shift its allocation or select one instead of the other. Check predictive stability and selection frequency separately rather than interpreting one selected list as the unique scientific explanation.

Practice 3

For α=0.4 and l1_ratio=0.25, identify the absolute and squared penalty multipliers.

Answer: The absolute-value multiplier is 0.4×0.25=0.1. The squared-norm multiplier is 0.4×0.75/2=0.15. These accompany squared error divided by 2n. Stating all three pieces prevents confusion with libraries or estimators that use a different loss normalization.

Practice 4

A fit returns a convergence warning but a good validation score. What should the author report and investigate?

Answer: Report the warning rather than concealing it. Check scaling, optimization tolerance, iteration limits, and solution stability, then rerun a justified configuration within development. A good score does not establish that the claimed numerical optimum was reached. Preserve the final test while addressing this training-process issue.

Five multiple-choice questions

Question 1

What distinguishes the lasso penalty?

  • A. Sum of absolute coefficients
  • B. Sum of squared coefficients only
  • C. Sum of squared residuals alone

Correct: A. The absolute coefficient penalty can produce exact zeros; the squared residual term still measures data fit.

Question 2

Does a zero lasso coefficient prove no causal effect?

  • A. Yes, if validation error is low
  • B. No, it reflects this fitted penalized representation
  • C. Yes, after standardization

Correct: B. Correlation, representation, sampling, and penalty choice all affect selection. Causality is a separate question.

Question 3

Which l1_ratio matches lasso in ElasticNet?

  • A. 0.5
  • B. 0
  • C. 1

Correct: C. At one, the squared coefficient component disappears and the objective becomes the lasso objective.

Question 4

Can Ridge and Lasso α values be compared directly without reading objectives?

  • A. Yes, if the target is centered
  • B. Yes, because both use alpha
  • C. No, their normalization and penalties differ

Correct: C. The same parameter name does not establish the same optimization convention or effective strength.

Question 5

What should a convergence warning trigger?

  • A. A numerical investigation
  • B. Automatic deletion of correlated rows
  • C. An assumption that all zero coefficients are exact truths

Correct: A. Verify the fitting process before relying on its coefficients, while preserving an honest evaluation boundary.

Common pitfalls

Do not perform feature selection on the full dataset before splitting. Do not treat a sparse feature list as uniquely identified when inputs overlap. Avoid using a zero penalty with a coordinate-descent lasso solver when ordinary least squares is the intended model.

Summary

Lasso promotes sparse solutions; elastic net combines sparsity with squared-coefficient shrinkage. Match objective conventions, scale deliberately, check convergence, and assess both predictions and selection stability. A compact model remains a model, not a causal certificate.

Primary sources and further reading