AI Wiki中文/EN

Elastic net: sparse weights that can share correlated signals

Elastic Net

Derive the mixed penalty, fit it with coordinate descent and distinguish conditional grouping from causal importance.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two copies of a sensor should not create two independent discoveries

Suppose a small teaching dataset contains two identical sensor columns and an unrelated alternating column. The target is 10 plus three times the sensor reading:

First sensorDuplicate sensorAlternating columnTarget
−1−1−17
−1−117
11−113
11113

Both sensor columns explain exactly the same variation. An L1 penalty can leave several equally good ways to divide their combined coefficient. A positive L2 penalty makes unequal divisions more expensive, while L1 can still set coefficients to zero. This combination is elastic-net regularization.

It does not establish that either sensor causes the target. Nor does the artificial duplicate represent two independent measurements. The example isolates a question about the fitted model: how should a penalty distribute weight across interchangeable columns?

Zou and Hastie’s 2005 paper studied this grouping effect. Its terminology needs care: the paper first defines a combined penalized objective, called the naïve elastic net, and later rescales its solution. The modern API convention used below minimizes the combined objective directly; we do not apply the paper’s separate rescaling. Original paper, §§2.1, 2.3 and 3.2.

Specify the penalty before naming its parameters

Let ZZ be the feature matrix on which the penalty is defined. We center its columns, optionally scale them, and keep an unpenalized intercept β0\beta_0. Our objective is:

F(β0,w)=∥y−β01−Zw∥222n+λρ∥w∥1+λ(1−ρ)2∥w∥22,λ>0,0≤ρ≤1.F(\beta_0,w)=\frac{\|y-\beta_0\mathbf1-Zw\|_2^2}{2n}+\lambda\rho\|w\|_1+\frac{\lambda(1-\rho)}2\|w\|_2^2,\qquad\lambda>0,\quad0\le\rho\le1.

Write a=λρa=\lambda\rho and b=λ(1−ρ)b=\lambda(1-\rho). The L1 threshold is controlled by aa; quadratic shrinkage is controlled by bb. Pure Lasso has ρ=1\rho=1, and the ridge endpoint has ρ=0\rho=0. Changing the ratio while holding lambda fixed changes both penalty components. Lambda zero gives unregularized least squares mathematically; this teaching implementation requires a positive value.

QuantityThis chapterscikit-learn ElasticNet
Overall penalty strengthlambdaalpha
L1 mixing fractionrhol1_ratio

The official 1.7.2 documentation uses exactly this loss normalization and half-factor on L2. It also explains that glmnet calls the overall strength lambda and its mixing fraction alpha. A parameter named alpha therefore has no universal meaning. Official objective and parameter conventions.

If the loss is written as a sum of squares rather than divided by 2n2n, preserving the same minimizer requires L1 coefficient 2na2na and L2 coefficient nbnb. Feature normalization must also agree. The original paper scales columns to unit Euclidean norm; our default scales nonconstant columns to unit population variance. Its additional factor 1+λ21+\lambda_2 belongs to its own rescaled estimator and notation, not an extra instruction to append to this program.

Because centered columns have mean zero, optimizing the unpenalized intercept gives β0=yˉ\beta_0=\bar y. For raw feature jj, store its training mean μj\mu_j and scale sjs_j. Fit on (xj−μj)/sj(x_j-\mu_j)/s_j; then the raw coefficient is wj/sjw_j/s_j and the raw intercept is yˉ−∑jμjwj/sj\bar y-\sum_j\mu_jw_j/s_j. The default scale is the square root of the mean squared centered value, using denominator nn. Constant columns become zero and use scale one. With standardize=False, we still center but use scale one for every column.

Penalties act on the fitted coordinates. A change from metres to millimetres can change an unstandardized fit even though the information is the same. Use training means and scales for later predictions. When choosing hyperparameters by validation, fit those transformations within the training portion of each split; do not let held-out observations determine them.

For one coordinate, remove its current contribution from the residual. With r−j=y−yˉ−∑k≠jZkwkr_{-j}=y-\bar y-\sum_{k\ne j}Z_kw_k, define cj=ZjTr−j/nc_j=Z_j^Tr_{-j}/n and qj=ZjTZj/nq_j=Z_j^TZ_j/n. Its objective slice is a quadratic plus an absolute value, giving:

wj←S(cj,a)qj+b,S(c,a)=sign⁡(c)max⁡(∣c∣−a,0).w_j\leftarrow\frac{S(c_j,a)}{q_j+b},\qquad S(c,a)=\operatorname{sign}(c)\max(|c|-a,0).

The denominator is positive for a nonzero column or positive L2 component. The remaining case is a zero column at the Lasso endpoint: its optimal coefficient is zero because a>0a>0. One exact coordinate update cannot increase the objective. Repeated sweeps are useful, but a small change in coefficients is not by itself our acceptance test.

Let r=y−yˉ−Zwr=y-\bar y-Zw and gj=ZjTr/n−bwjg_j=Z_j^Tr/n-bw_j. Convex optimality requires the following residual to be zero for every coordinate:

ej={∣gj−asign⁡(wj)∣,wj≠0,max⁡(0,∣gj∣−a),wj=0.e=max⁡jej.e_j=\begin{cases}|g_j-a\operatorname{sign}(w_j)|,&w_j\ne0,\\\max(0,|g_j|-a),&w_j=0.\end{cases}\qquad e=\max_j e_j.

At a zero coefficient, the correlation with the current residual must fit inside the L1 threshold. These are the Karush–Kuhn–Tucker (KKT) conditions, and for this convex objective they are sufficient as well as necessary. With no features, define the maximum residual as zero. A positive bb makes the coefficient objective strongly convex, so its minimizer is unique even if the columns are dependent. At the Lasso endpoint, uniqueness can fail.

For the grouping calculation, assume two nonconstant standardized columns have squared norm nn, and their optimal coefficients are nonzero with the same sign. Subtract their KKT equations. If cjk=ZjTZk/nc_{jk}=Z_j^TZ_k/n and b>0b>0, Cauchy–Schwarz gives:

b(wj−wk)=(Zj−Zk)Trn,∣wj−wk∣≤∥r∥2n2(1−cjk)b.b(w_j-w_k)=\frac{(Z_j-Z_k)^Tr}{n},\qquad |w_j-w_k|\le\frac{\|r\|_2}{\sqrt n}\frac{\sqrt{2(1-c_{jk})}}b.

The shared L1 sign cancels; column normalization gives the squared difference norm 2n(1−cjk)2n(1-c_{jk}). This is the grouping argument in our normalization. It does not apply unchanged when a coefficient is zero, signs differ, or b=0b=0. A small L2 component can also make the bound loose. For identical columns, equality of the optimal coefficients follows without the same-sign assumption: averaging their coefficients preserves predictions, cannot increase L1, and strictly decreases L2 unless they were already equal. Negatively correlated columns may instead have coefficients of opposite signs. Grouping conditions and proof in the original paper, §2.3 and Appendix A.

Stop on a stated numerical condition

The complete standard-library implementation uses cyclic coordinate descent, beginning at zero. It refreshes the residual after each sweep to limit accumulated update error. converged means the computed maximum KKT residual is at most tol; it does not certify exact real-arithmetic optimality. Exhausting max_sweeps returns max-iterations with the current coefficients and residual, rather than silently labelling them converged.

The initial zero vector is checked before a sweep. Thus a zero sweep budget can be sufficient when the penalty already makes zero optimal, and insufficient otherwise. This stopping rule is not scikit-learn’s update-plus-dual-gap rule, so identical tolerance numbers do not mean identical acceptance tests.

Inputs are finite int/float values in rectangular lists or tuples, excluding booleans. At least one observation is required; zero features give an intercept-only fit. Nonfinite intermediate arithmetic and detected variance, norm or penalty underflow raise ValueError. Ordinary floating-point rounding still remains. predict expects an unchanged model returned by fit, not an arbitrary edited dictionary.

# Python 3.10+; dense, single-output regression with an unpenalized intercept.
from math import copysign, fsum, isfinite, sqrt


def number(value):
    if type(value) not in (int, float):
        raise ValueError('use finite int/float values, not booleans')
    try:
        value = float(value)
    except OverflowError as error:
        raise ValueError('number is outside floating-point range') from error
    if not isfinite(value):
        raise ValueError('nonfinite numerical value; rescale the data')
    return value


def total(values):
    try:
        return number(fsum(values))
    except (ValueError, OverflowError) as error:
        raise ValueError('numerical range exceeded; rescale the data') from error


def sequence(values):
    if type(values) not in (list, tuple):
        raise ValueError('use a list or tuple')
    return tuple(number(x) for x in values)


def soft(value, threshold):
    return copysign(max(abs(value) - threshold, 0.0), value)


def fit(X, y, lam=1.0, l1_ratio=0.5, standardize=True,
        tol=1e-10, max_sweeps=10000):
    if type(X) not in (list, tuple) or not X:
        raise ValueError('X must have at least one row')
    X = tuple(sequence(row) for row in X)
    y = sequence(y)
    n, p = len(X), len(X[0])
    if len(y) != n or any(len(row) != p for row in X):
        raise ValueError('inconsistent shapes')
    lam, mix, tol = number(lam), number(l1_ratio), number(tol)
    if lam <= 0 or not 0 <= mix <= 1 or tol <= 0:
        raise ValueError('require lambda > 0, ratio in [0,1], tolerance > 0')
    if type(standardize) is not bool:
        raise ValueError('standardize must be Boolean')
    if type(max_sweeps) is not int or max_sweeps < 0:
        raise ValueError('max_sweeps must be a nonnegative integer')
    y_mean = y[0] if all(v == y[0] for v in y) else total(v / n for v in y)
    target = tuple(number(v - y_mean) for v in y)
    means, scales, columns, norms = [], [], [], []
    for j in range(p):
        values = tuple(row[j] for row in X)
        constant = all(v == values[0] for v in values)
        mean = values[0] if constant else total(v / n for v in values)
        centered = tuple(number(v - mean) for v in values)
        scale = 1.0
        if standardize and not constant:
            scale = sqrt(total(v * v / n for v in centered))
            if scale == 0:
                raise ValueError('nonconstant column variance underflow')
        column = tuple(number(v / scale) for v in centered)
        means.append(mean); scales.append(scale); columns.append(column)
        norms.append(total(v * v / n for v in column))
        if not constant and norms[-1] == 0:
            raise ValueError('nonconstant column norm underflow')
    a, b = lam * mix, lam * (1 - mix)
    if (mix > 0 and a == 0) or (mix < 1 and b == 0):
        raise ValueError('penalty underflow; rescale lambda')
    weights, residual = [0.0] * p, list(target)

    def kkt_error():
        errors = []
        for j, w in enumerate(weights):
            c = total(x * r / n for x, r in zip(columns[j], residual)) - b * w
            errors.append(abs(c - copysign(a, w)) if w != 0
                          else max(0.0, abs(c) - a))
        return number(max(errors, default=0.0))

    error, sweeps = kkt_error(), 0
    while error > tol and sweeps < max_sweeps:
        for j, column in enumerate(columns):
            old = weights[j]
            c = total(x * (r + x * old) / n for x, r in zip(column, residual))
            denominator = number(norms[j] + b)
            new = 0.0 if denominator == 0 else number(soft(c, a) / denominator)
            residual = [number(r - x * (new - old)) for x, r in zip(column, residual)]
            weights[j] = new
        # Rebuild once per sweep to limit drift from incremental updates.
        residual = [number(target[i] - total(columns[j][i] * weights[j]
                    for j in range(p))) for i in range(n)]
        sweeps += 1
        error = kkt_error()
    coef = tuple(number(w / scale) for w, scale in zip(weights, scales))
    intercept = number(y_mean - total(m * w for m, w in zip(means, coef)))
    objective = total(r * r / (2 * n) for r in residual)
    objective = number(objective + a * total(abs(w) for w in weights)
                       + b * total(w * w for w in weights) / 2)
    return dict(status='converged' if error <= tol else 'max-iterations',
                sweeps=sweeps, kkt_error=error, objective=objective,
                coef=coef, intercept=intercept, weights=tuple(weights),
                means=tuple(means), scales=tuple(scales))


def predict(model, rows):
    if type(rows) not in (list, tuple):
        raise ValueError('prediction rows must be a list or tuple')
    output = []
    for row in rows:
        row = sequence(row)
        if len(row) != len(model['coef']):
            raise ValueError('wrong prediction width')
        output.append(number(model['intercept'] + total(
            x * w for x, w in zip(row, model['coef']))))
    return tuple(output)


if __name__ == '__main__':
    X = ((-1, -1, -1), (-1, -1, 1), (1, 1, -1), (1, 1, 1))
    y = (7, 7, 13, 13)
    for ratio in (1.0, 0.5):
        model = fit(X, y, lam=1, l1_ratio=ratio)
        print('ratio:', ratio, 'status:', model['status'])
        print('weights:', tuple(round(w, 8) for w in model['weights']))
        print('intercept:', round(model['intercept'], 8))
        print('predictions:', tuple(round(v, 8) for v in predict(model, X)))
    limited = fit(X, y, max_sweeps=1)
    print('one sweep:', limited['status'], 'KKT error:', round(limited['kkt_error'], 8))

The program prints rounded coefficients and predictions:

ratio: 1.0 status: converged
weights: (2.0, 0.0, 0.0)
intercept: 10.0
predictions: (8.0, 8.0, 12.0, 12.0)
ratio: 0.5 status: converged
weights: (1.0, 1.0, 0.0)
intercept: 10.0
predictions: (8.0, 8.0, 12.0, 12.0)
one sweep: max-iterations KKT error: 0.55555556

For pure Lasso, this cyclic solver selects the first duplicate and assigns it weight two. Every nonnegative split of total weight two is also optimal, including one and one. The elastic-net objective with a=b=1/2a=b=1/2 has the unique duplicate weights one and one. The unrelated column remains zero. Intercept ten is not shrunk.

The predictions happen to match at these chosen parameters; that is a property of this constructed example, not a general equality between Lasso and elastic net. Comparing objective values across different penalty settings would not establish which predicts better. The one-sweep result visibly fails the KKT tolerance.

With SS completed sweeps, dense fitting takes O((S+1)n(p+1))O((S+1)n(p+1)) arithmetic operations and O(n(p+1))O(n(p+1)) space, where pp is the feature count. This includes preparation and the initial optimality check, including zero features or zero sweeps. It is not a bound on how many sweeps a requested tolerance will need. Prediction on mm rows takes O(1+m(p+1))O(1+m(p+1)) operations.

The independent test reference enumerates small active-sign patterns, solves each candidate’s normal equations with exact rational arithmetic, and checks the remaining KKT inequalities. It does not run another coordinate-descent loop. Centering-only integer datasets keep that reference rational; the standardized duplicate example also has exact unit scales.

Stable weights are not proof of a correct explanation

Correlated predictors can enter together and still be proxies for something unmeasured. Equal coefficients depend on the penalty and coordinate scale, not evidence that two variables have equal causal importance. The method also remains a linear predictor: interactions, nonlinear responses and changes in the data-generating process require separate examination.

L1 can remove variables, including useful ones when regularization is too strong. L2 improves uniqueness but can spread weight across redundant measurements. Duplicating columns changes the penalty geometry and may change predictions. No setting is uniformly best across datasets.

Choose lambda and the mixing ratio using a validation design appropriate to the intended prediction task, keeping the test set outside that choice. Report predictive error, selected coefficients, transformations and convergence status. For this four-row illustration, the calculation is about optimization and dependence; it is not a performance study or a hyperparameter recommendation.

The implementation has no sample weights, sparse matrices, warm starts or regularization-path machinery. To compare its objective with the documented API, use the same transformed matrix and centered target, alpha=lambda, l1_ratio=rho and fit_intercept=False, then restore the saved centering. The API was consulted for conventions; no scikit-learn execution is claimed here.

Predict the effect before rerunning the fit

Exercise 1: translate two separate penalty coefficients

Answer: If the objective has 0.3∥w∥1+0.5×0.7∥w∥220.3\|w\|_1+0.5\times0.7\|w\|_2^2 after the mean squared loss, then lambda is 1 and rho is 0.3. The documented scikit-learn arguments are alpha=1 and l1_ratio=0.3. Multiplying the loss by 2n2n requires multiplying both penalties by that factor too.

Exercise 2: multiply the first sensor column by 1000

Answer: With training standardization enabled, its transformed column stays the same. Its raw coefficient is divided by 1000 and predictions remain the same, up to rounding. Without standardization, the same lambda and ratio describe a different penalty on the predictor’s effect, so the fit need not agree.

Exercise 3: why are the duplicate elastic-net weights equal?

Answer: Their sum controls the prediction. At a fixed sum, averaging cannot increase the absolute-value penalty and minimizes the positive quadratic penalty. Unequal weights therefore cannot minimize the combined objective. For the displayed data, the common positive weight solves (2+0.5)w=3−0.5(2+0.5)w=3-0.5, so each is one. Removing L2 permits the Lasso’s nonunique splits.

Exercise 4: one sweep finishes without an exception—is the fit accepted?

Answer: No. Its status is max-iterations and its KKT residual is about 0.556, far above the default tolerance. More sweeps may resolve this numerical issue; they do not prove that the model generalizes. Conversely, an initial zero vector that already meets the KKT tolerance can be accepted with zero sweeps.

Read the estimator definition alongside its implementation

Zou and Hastie, Regularization and variable selection via the elastic net, JRSS B 67(2), 301–320 (2005), author-hosted journal copy, separates the combined penalty from the rescaled estimator and introduces LARS-EN. The same year’s addendum corrects the attribution of Lasso path results to include Osborne and colleagues. It does not change the objective developed here.

The scikit-learn 1.7.2 ElasticNet documentation fixes the API parameter convention and its distinct stopping criterion. Our data, derivation in mean-loss notation, program and exercises are original. Revisit linear regression, ridge regression and Lasso for the separate ingredients.

Make a prediction, then check

After dividing squared error by 2n, the penalty is 0.3 times L1 plus 0.7 times squared L2 divided by 2. Which parameters match?

Choose one answer

Learning objectives

  • Translate lambda, L1 ratio and both penalties while accounting for mean loss, intercept and training standardization.
  • Derive the coordinate soft-threshold update and KKT stopping condition, separating numerical convergence, iteration limits and generalization.
  • Prove equal weights for identical columns with positive L2 and state the same-sign, nonzero and normalization conditions for the near-collinearity bound.

Prerequisites & connections

Explore related knowledge →

References

  1. Regularization and variable selection via the elastic net
    Hui Zou; Trevor Hastie · 2005
  2. scikit-learn 1.7.2 — ElasticNet
    scikit-learn developers
  3. Addendum: Regularization and Variable Selection Via the Elastic Net
    Hui Zou; Trevor Hastie · 2005

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • All eight standard-library tests passed. Twenty-five exact reference fits enumerated 675 active-sign patterns and used Fraction Gaussian elimination plus full KKT inequalities to check coefficients, intercept and objective. The reference does not reuse coordinate descent. Cases include 24 integer datasets using seed 50021 and the unit-scale duplicate-column example.
  • Checked nonunique Lasso allocations, equal weights with positive L2, the same-sign near-collinearity bound, opposite signs under negative correlation, unit changes, repeated-sample mean-loss invariance, constant columns and intercept-only models. Zero/one-sweep boundaries, 18 invalid or numerical-range inputs and input preservation passed; all nine stdout lines match.
  • Both languages contain six anchors, four identical display equations, identical complete code/output and four answered exercises. Actual strict MDX/KaTeX/React HTML passed; decoded MathML formulas match the source without emphasis remnants outside code. Numerical tolerance is not presented as a real-arithmetic proof or the official dual-gap test.
  • Reread paragraphs using the fixed Humanizer rules. Examples and code are original; source scope and versions are recorded accurately. AI author self-check only, review remains written pending independent review. No scikit-learn execution, whole-site build, browser acceptance or real-sensor experiment.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.

Source locations checked:

  • Regularization and variable selection via the elastic net · Actually opened the author-hosted 20-page journal PDF after the Stanford redirect failed. Read §2.1, printed p. 303, web lines 88–132: centering, unit-norm columns and the sum-of-squares mixed penalty. Read §2.3, p. 306, lines 212–268: identical-column strict convexity and the same-sign condition for the grouping bound. Read §3.2, pp. 307–308, lines 303–327: the separate 1+lambda2 rescaling. Appendix A, pp. 318–319, lines 783–858 supplies averaging and stationarity arguments. Formula extraction was imperfect; the article independently derives its mean-loss normalization. No source figure or code copied; no full-paper visual audit claimed.
  • scikit-learn 1.7.2 — ElasticNet · Actually read official 1.7.2 API content at web lines 625–657: mixed objective, parameter mapping, endpoints and intercept; lines 672–749: tolerance, cyclic selection and update-plus-dual-gap stopping; lines 768–808: coordinate-descent fitting. The teaching solver deliberately uses an absolute KKT residual instead, which is disclosed. No upstream implementation was executed.
  • Addendum: Regularization and Variable Selection Via the Elastic Net · Actually read the publisher’s public extract at web lines 36–50: JRSS B 67(5), November 2005, p. 768, and the missing attribution to Osborne et al. (2000). The visible correction concerns path-result attribution; the article does not claim its solver implements LARS-EN.
  • Regularization and variable selection via the elastic net · Author-hosted journal PDF text: §2.1 printed303, §2.3 printed306, §3.2 printed307–308. Checked objective conventions, same-sign grouping premise, identical-column argument and separate rescaling. Independently derived the article constants; no full visual audit claimed.
  • scikit-learn 1.7.2 — ElasticNet · Official page displaying1.7.2: objective and parameter/intercept entries625–657, tolerance/cyclic selection/dual-gap notes672–749; fitting described as coordinate descent. Read only; did not execute sklearn.
  • Addendum: Regularization and Variable Selection Via the Elastic Net · Publisher public extract36–50: November2005 p768 and Osborne path attribution correction. No paid full-text claim.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.