Lasso regression
Lasso 回归
Derive soft thresholding and KKT checks, fit an unpenalized intercept, and separate sparse coefficients from unique scientific explanations.
lassoA small coefficient can become exactly zero
Suppose a small forecasting model uses two centered features. Ordinary least squares assigns them coefficients 3 and . You want to trade some training fit for a model that uses fewer features. Lasso imposes a cost on the sum of absolute coefficient values. Unlike ordinary ridge shrinkage, its optimum can land exactly at zero.
Consider four invented observations with feature rows and responses . With the average-loss convention below and penalty , Lasso selects coefficients . The first effect is reduced; the second disappears. This happens because of the penalty’s shape, not because the second feature has been proved irrelevant to the world.
The name abbreviates “least absolute shrinkage and selection operator.” Tibshirani’s 1996 paper, Sections 1–2 introduced the method through a bound on the sum of absolute coefficients. Here we use the related penalized form to derive a directly runnable algorithm.
Use a subgradient at the corner
For observations , responses , an intercept and coefficients , define
The intercept is not penalized. The factor fixes the meaning of ; a summed loss would require a correspondingly rescaled penalty to describe the same optimization. The squared loss is convex, and so is the absolute-value penalty. No Gaussian assumption is needed to define this estimator, though a Gaussian observation model gives a likelihood interpretation.
At a nonzero coefficient the derivative of its absolute value is its sign. At zero, the relevant convex subgradient is an interval:
Let and . The smooth loss gradient in coordinate is , so optimality requires . Thus
The final condition belongs to the intercept. These are the Karush–Kuhn–Tucker, or KKT, conditions for this unconstrained convex objective. They are necessary and sufficient for a global minimum. A small coefficient alone does not establish that it should be zero: its residual correlation must fit inside the interval.
Minimizing over gives . Equivalently, center every feature and the response, solve without an intercept, and transform back. Hold all coordinates except fixed. With centered data and partial residual excluding feature , set
Up to a constant, the one-coordinate problem becomes . Solving separately on the positive side, negative side and at zero gives
This is soft thresholding: subtract a threshold from the magnitude, then clip at zero. It differs from hard thresholding, which either retains an unchanged coefficient or discards it. If a centered column is identically zero, and its penalized optimum is . Friedman, Hastie and Tibshirani’s 2009 manuscript, equations 5–8 develops the coordinate update and residual implementation; its standardized-column denominator must be adjusted to for general columns.
In the opening example, and initial correlations are . Thresholding by gives . Its residual is , with correlations : the active and inactive KKT conditions both hold. Its objective is . At , both coefficients are zero. Generally, centered coefficients are all zero at
Update a coordinate, then check the whole problem
This complete standard-library program centers the data, cycles through coordinates, and tracks residuals. It reports a KKT violation after recomputing residuals from scratch. Returning a tolerance and sweep count makes the numerical stopping decision visible; a maximum-iteration failure raises an error. The example uses dense input arrays and does not implement sparse-matrix acceleration.
import math
def soft_threshold(z, penalty):
return math.copysign(max(abs(z)-penalty,0.0),z)
def lasso_coordinate(x,y,penalty,tol=1e-9,max_sweeps=10000):
x = [list(map(float,row)) for row in x]
y = list(map(float,y))
n = len(y)
if not n or len(x) != n or not x[0]:
raise ValueError("nonempty matching data required")
p = len(x[0])
if any(len(row) != p for row in x):
raise ValueError("rectangular features required")
if not all(math.isfinite(v) for row in x for v in row) or not all(map(math.isfinite,y)):
raise ValueError("finite data required")
if not math.isfinite(penalty) or penalty <= 0 or not math.isfinite(tol) or tol <= 0:
raise ValueError("finite positive penalty and tolerance required")
if type(max_sweeps) is not int or max_sweeps < 1:
raise ValueError("positive integer iteration limit required")
means = [math.fsum(row[j] for row in x)/n for j in range(p)]
mean_y = math.fsum(y)/n
columns = [[row[j]-means[j] for row in x] for j in range(p)]
target = [v-mean_y for v in y]
norms = [math.fsum(v*v for v in col)/n for col in columns]
if any(not math.isfinite(d) or (d == 0 and any(col)) for d,col in zip(norms,columns)):
raise ValueError("column scale is outside this numerical example's range")
weights = [0.0]*p
residual = target.copy()
for sweep in range(1,max_sweeps+1):
for j,col in enumerate(columns):
if norms[j] == 0:
continue
z = math.fsum(v*r for v,r in zip(col,residual))/n+norms[j]*weights[j]
new = soft_threshold(z,penalty)/norms[j]
change = new-weights[j]
weights[j] = new
residual = [r-change*v for r,v in zip(residual,col)]
# Recompute before checking all KKT conditions; avoid accumulated drift.
residual = [target[i]-math.fsum(columns[j][i]*weights[j] for j in range(p)) for i in range(n)]
correlations = [math.fsum(v*r for v,r in zip(col,residual))/n for col in columns]
violation = max(abs(c-penalty*math.copysign(1,w)) if w else max(abs(c)-penalty,0)
for c,w in zip(correlations,weights))
violation = max(violation,abs(math.fsum(residual)/n))
if not all(map(math.isfinite,residual+weights+correlations)):
raise ValueError("nonfinite intermediate result; rescale the data")
if violation <= tol:
intercept = mean_y-math.fsum(m*w for m,w in zip(means,weights))
objective = math.fsum(r*r for r in residual)/(2*n)+penalty*math.fsum(abs(w) for w in weights)
if not math.isfinite(intercept) or not math.isfinite(objective):
raise ValueError("nonfinite output; rescale the data")
return intercept,weights,objective,violation,sweep
raise RuntimeError("KKT tolerance not reached within max_sweeps")
x = [(1,0),(-1,0),(0,1),(0,-1)]
y = [3,-3,.5,-.5]
b,w,value,kkt,sweeps = lasso_coordinate(x,y,.5)
assert b == 0 and w == [2,0]
assert value == 21/16 and kkt <= 1e-9
shifted = lasso_coordinate(x,[v+7 for v in y],.5)
assert shifted[0] == 7 and shifted[1] == w
assert lasso_coordinate(x,y,1.5)[1] == [0,0]
One full sweep costs arithmetic. With sweeps, the cost is and copied-data storage is . These counts do not make independent of feature correlations or tolerance. Cyclic updates decrease the objective in exact arithmetic, but small floating-point changes are not a convergence certificate. The reported KKT tolerance is an approximate stationarity check, not a formal floating-point error bound on every coefficient.
The program deliberately requires and leaves ordinary least squares to its own solver. It detects a column whose squared norm underflows to zero despite nonzero entries, and rejects nonfinite intermediate results. Extreme scales can still cause loss of accuracy or arithmetic exceptions; use moderate teaching data and rescale before interpreting tiny differences. Recomputing residuals reduces accumulated drift but does not remove all rounding error.
Sparsity depends on the variables you chose
Feature scale changes the penalty’s meaning. Multiplying a feature by ten permits its coefficient to shrink tenfold while preserving predictions, lowering its contribution to . Automatic standardization therefore changes which effects compete on equal terms. Estimate any scaling on training data and apply the same transformation to later data. A constant column must be handled explicitly. The coordinate-descent manuscript, Section 2.6 distinguishes centering, standardization and the unpenalized intercept.
A positive penalty ensures an attained minimum for finite data with : objective sublevel sets bound , and minimizing the intercept is explicit. It does not ensure unique coefficients. If two columns are identical, a positive combined coefficient can be divided between them in many ways with the same fit and the same L1 penalty. Strict convexity of squared error ensures a unique fitted vector across minimizers, not necessarily a unique coefficient vector. A positive L2 component in an elastic-net penalty can remove this coefficient degeneracy.
Selected features can be unstable when alternatives explain almost the same direction. The orthogonal example is easy precisely because its coordinates decouple; do not transfer all of its behavior to correlated features.
The constrained form minimizes squared error subject to . A Lagrange multiplier connects it to a penalized problem under the usual convex conditions, but and need not form a strict one-to-one correspondence. The original paper’s orthonormal-design discussion, Section 2.2 gives the clean soft-thresholding case. Shrinkage biases the retained coefficients; sparse selection is neither proof of causality nor a general guarantee of recovering the true feature set.
Inspect what made a coefficient vanish
- In the opening example, why is the second coefficient zero at ? Answer: its partial-residual correlation is , inside . Zero satisfies the subgradient condition.
- What changes if 7 is added to all four responses? Answer: the unpenalized intercept becomes 7, while the centered problem and coefficients remain unchanged.
- What is the smallest penalty making both coefficients zero? Answer: . It is the largest absolute centered feature–response correlation divided by .
- Two columns are identical and an optimum has coefficients . Can have the same objective? Answer: yes. The fitted contribution and L1 sum are unchanged. Exact sparsity does not imply uniqueness of the chosen variables.
Use the zero pattern as a hypothesis to examine
Lasso links convex optimization, sparse representations and statistical model selection. Coordinate descent exploits the separable penalty, while active-set methods and warm starts can accelerate a sequence of related fits. The geometry also connects it to proximal methods: soft thresholding is the proximal operator of a scaled L1 norm. These are routes to implementation, not evidence that one selected set is scientifically correct.
Compare a fitted model against an intercept-only baseline, ordinary least squares when appropriate, and ridge or elastic net using a valid validation split. Look at prediction error and selection stability, and keep any final test data outside penalty tuning. If a scientific interpretation depends on a specific coefficient being present, investigate that claim separately from the predictive advantage of the whole model.
Make a prediction, then check
With average squared loss plus lambda times the L1 penalty, a zero coefficient has residual correlation lambda/2. Does that coordinate satisfy its optimality condition?
Learning objectives
- Derive zero and nonzero KKT conditions from the L1 subgradient, retaining the general column squared-norm denominator.
- Implement centering, an unpenalized intercept and coordinate descent, then reconstruct residuals to check the stopping condition.
- Distinguish sparsity, coefficient uniqueness, fitted-value uniqueness and scientific interpretation, explaining how feature scaling changes the penalty.
Prerequisites & connections
- Linear regression
- Derivatives and local approximation
- Convex sets and functions
- Inner products and angles
References
- Regression Shrinkage and Selection via the Lasso
Robert Tibshirani · 1996 - Regularization Paths for Generalized Linear Models via Coordinate Descent — author manuscript, 29 April 2009
Jerome Friedman; Trevor Hastie; Robert Tibshirani · 2009
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex multi-agent technical check: primary-source verification, derivation and numerical assertions, bilingual comparison, and review by another agent or the parent; no independent human peer review.
- Checked the specified original-paper and manuscript pages; independently derived the subgradient, general denominator, centering, maximum threshold, existence and fitted-value uniqueness.
- Used exact fractions to enumerate all two-coordinate active/sign patterns for the 79 nondegenerate cases among 80 generated small random datasets, comparing coefficients, intercepts, objectives and raw-data KKT conditions; checked duplicate and constant columns, feature-unit changes and threshold boundaries.
- Compared bilingual prose paragraph by paragraph; code and display equations match exactly, six anchors and four answers pass structural checks, and all math expressions compile with KaTeX.
- Another agent read the original journal scan and 2009 author manuscript and executed eight algorithm checks; λmax display punctuation was aligned, and 79 nondegenerate oracle cases were not reported as 80.
- The parent executed all 37 independent classical-method checks successfully; bilingual code, display equations, six main anchors and four answered exercises were individually compared.
Source locations checked:
- Regression Shrinkage and Selection via the Lasso · Inspected scan PDF pp. 1–4, including the cover and printed journal pp. 267–269 (sections 1, 2.1 and 2.2): original name, constrained coefficient sum, centered predictors, unpenalized intercept, and orthonormal soft-thresholding case. Scan read at https://hedibert.org/wp-content/uploads/2018/05/tibshirani-1996.pdf; canonical citation points to the publisher. No claim to have reviewed all 23 scan pages.
- Regularization Paths for Generalized Linear Models via Coordinate Descent — author manuscript, 29 April 2009 · 2009-04-29 author manuscript, PDF pp. 3–4 section 2 equations 1–4, p. 6 equations 5–8 and p. 8 section 2.6: L1 objective, soft thresholding, partial residual updates, standardization and unpenalized intercept. Derived the general column denominator d_j explicitly. The manuscript describes X^T r/n as a gradient despite r=y−Xw; the article uses the correct negative sign for the smooth-loss gradient. Did not reuse its inaccurate fixed-lambda duplicate-column ridge comparison.
Related topics