Lasso and sparsity
Quick answer
Lasso regression adds an L1 penalty, the sum of absolute feature weights, to a squared prediction loss. Unlike ridge, this objective can put some weights exactly at zero, producing a sparse model. Examples are standalone local Python 3.13.5 snippets; library examples use scikit-learn 1.8.0. ByteMind execution is unverified.
Soft threshold a correlation score
def soft(z, a): return (1 if z >= 0 else -1)*max(abs(z)-a, 0)print([soft(z, 1) for z in [3, -4, 1, 0]])Expected output:
[2, -3, 0, 0]Both signs shrink toward zero, and values at the threshold vanish.
How it works
For n training rows, scikit-learn Lasso uses SSE/(2n) + alpha * sum(abs(w_j)). The loss normalization differs from Ridge, so equal alpha values are not equal penalties. The kink of |w| at zero makes zero a possible optimum. Consider one centered feature with mean(xx)=1 and z=mean(xy). Its coefficient solves 0.5(w-z)**2 + alpha*abs(w) up to a constant; the answer is sign(z)*max(abs(z)-alpha,0), called soft thresholding. If z=3 and alpha=1, w=2; if z=-0.5, alpha=1 gives zero. This formula applies directly only to a normalized orthogonal coordinate or a coordinate update with appropriate partial residuals, not to arbitrary correlated columns. Lasso solvers often update one coordinate at a time until a convergence condition is met. Strongly correlated features may substitute for one another; selection can change when data changes. A zero coefficient is not proof that a variable is irrelevant or causal. Scale numeric features inside the training pipeline, inspect convergence, and compare validation error across penalties.
Fit an orthogonal sparse example
from sklearn.linear_model import LassoX = [[-1,-1],[-1,1],[1,-1],[1,1]]y = [-2.5,-1.5,1.5,2.5]m = Lasso(alpha=1, fit_intercept=False, tol=1e-10).fit(X,y)print(m.coef_.round(6).tolist())Expected output:
[1.0, 0.0]The first feature correlation is 2 and the second is 0.5. L1 thresholding retains only the first.
Common mistakes
Do not interpret the chosen feature among near duplicates as the uniquely important feature. Check stability across training resamples. Do not assume a nonconverged fit is reliable just because predict() returns values.
Practice and next steps
Calculate soft thresholding for z=-5 at alpha=2, then at alpha=5. Explain why a zero fitted weight is not a causal finding. Complete the knowledge check and coding exercise. Next: Elastic Net.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Lasso and sparsity — knowledge check
Apply lasso and sparsity to new examples.
Which penalty produces Lasso sparsity?
Soft threshold z=-4 with alpha=1 gives?
When can the single-coordinate formula be applied independently to all columns?
What can happen with nearly duplicate predictors?
Why not compare Ridge alpha=1 directly with Lasso alpha=1?