AI Wiki中文/EN

Ridge regression

岭回归

Derive the centered ridge system and spectral shrinkage, solve redundant features exactly, and track how scaling and duplication change the penalty.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two identical features should not invent two explanations

A toy dataset has two observations. Both features equal −1 on the first observation and +1 on the second; the targets are −2 and +2. A zero-intercept model predicts w1x1+w2x2w_1x_1+w_2x_2. Every pair with w1+w2=2w_1+w_2=2 fits perfectly: (1,1), (100,−98), and many more. The training data cannot distinguish them.

Ridge regression adds a cost for large squared coefficients. With the convention below and λ=2, its unique solution is (2/3,2/3)(2/3,2/3). It accepts some residual error while keeping the coefficient norm small. This is an explicit modeling and tuning choice, not a discovery that either feature caused the target.

The quadratic penalty also stabilizes weakly observed directions. It helps explain why a linear model can have modest training error yet fragile coefficients. Hastie, 2020, Section 1 describes ridge through both the optimization objective and the shifted linear system.

Same λ, different predictions after duplication

00.511.5202468λCombined slope4/31
Blue solid: sum of the two duplicated coefficients. Orange dashed: single-column coefficient. Each line joins 33 computed points under the same λ convention.

State the loss scale and intercept policy first

Use an unpenalized intercept b and a positive penalty λ on all d slopes:

J(b,w)=12∑i=1n(yi−b−xi⊤w)2+λ2∥w∥22,λ>0.J(b,w)=\frac12\sum_{i=1}^n(y_i-b-x_i^\top w)^2+\frac\lambda2\|w\|_2^2,\qquad\lambda>0.

Here the data loss is a sum. If it is changed to a mean, use penalty λ/n to preserve the same solution. D2L uses an averaged loss, so its regularization coefficient must be translated before comparing formulas or implementations. D2L, equations 3.7.1–3.7.3

Differentiating with respect to b gives b=yˉ−xˉ⊤wb=\bar y-\bar x^\top w. Let Z be the column-centered design and yc=y−yˉ1y_c=y-\bar y\mathbf1. Substitute b back into J. The slope gradient and normal equations become

∇wJ=Z⊤(Zw−yc)+λw,(Z⊤Z+λI)w^=Z⊤yc.\nabla_wJ=Z^\top(Zw-y_c)+\lambda w,\qquad (Z^\top Z+\lambda I)\widehat w=Z^\top y_c.

For any nonzero v,

v⊤(Z⊤Z+λI)v=∥Zv∥2+λ∥v∥2>0.v^\top(Z^\top Z+\lambda I)v=\|Zv\|^2+\lambda\|v\|^2>0.

Thus the system is positive definite even when Z has redundant columns or more columns than rows. There is one slope solution, and for n>0 one corresponding intercept. Inverse notation is useful for analysis, but implementation should solve the system. MML derives the analogous shift from a Gaussian prior in equations 9.28–9.31; its displayed model penalizes all listed parameters, whereas this article explicitly leaves b unpenalized.

The singular-value decomposition shows what is shrunk. For a compact SVD Z=UDV⊤Z=UDV^\top retaining its r positive singular values djd_j,

w^λ=∑j=1rvjdjdj2+λuj⊤yc,Zw^λ=∑j=1rujdj2dj2+λuj⊤yc.\widehat w_\lambda=\sum_{j=1}^r v_j\frac{d_j}{d_j^2+\lambda}u_j^\top y_c,\qquad Z\widehat w_\lambda=\sum_{j=1}^r u_j\frac{d_j^2}{d_j^2+\lambda}u_j^\top y_c.

The fitted-data component in direction uju_j is multiplied by dj2/(dj2+λ)d_j^2/(d_j^2+\lambda). Small-singular-value directions shrink more. Original-coordinate coefficients need not each shrink monotonically in absolute value because they mix these directions. As λ approaches zero, slopes approach the minimum-norm least-squares solution; as λ grows without bound, slopes approach zero and the intercept approaches the training target mean. Hastie, Section 2, equations 9–10

For the two-column example, Z⊤ZZ^\top Z has every entry two, and Z⊤yc=(4,4)⊤Z^\top y_c=(4,4)^\top. Adding 2 to the diagonal gives a system with solution (2/3,2/3)(2/3,2/3). Its SSE is 8/9 and squared coefficient norm is 8/9, giving objective 4/3. The exact-fit vector (1,1) has zero SSE but objective two, so it loses under this penalty.

Solve a small singular-design example exactly

The complete program accepts rational data of any finite feature dimension, centers using the training observations, and solves the positive-definite system by exact elimination. Positive pivots follow from positive definiteness in exact arithmetic. This is a teaching implementation; its use of a Gram matrix and unpivoted elimination is not a recommendation for difficult floating-point problems.

from fractions import Fraction as F

def rational(v):
    if type(v) is not int and not isinstance(v,F):
        raise ValueError("integer or Fraction values required")
    return F(v)

def ridge_fit(rows, targets, penalty):
    X = [tuple(map(rational,row)) for row in rows]
    y = tuple(map(rational,targets))
    lam = rational(penalty)
    if not X or not X[0] or len(X)!=len(y) or lam<=0:
        raise ValueError("paired nonempty data, features and positive penalty required")
    n,d = len(X),len(X[0])
    if any(len(row)!=d for row in X):
        raise ValueError("rectangular design required")
    xm = [sum(row[j] for row in X)/n for j in range(d)]
    ym = sum(y)/n
    Z = [[row[j]-xm[j] for j in range(d)] for row in X]
    yc = [v-ym for v in y]
    G = [[sum(row[i]*row[j] for row in Z)+(lam if i==j else 0)
          for j in range(d)] for i in range(d)]
    rhs = [sum(row[j]*v for row,v in zip(Z,yc)) for j in range(d)]
    augmented = [row+[v] for row,v in zip(G,rhs)]
    # Exact elimination: SPD guarantees positive successive pivots.
    for k in range(d):
        pivot = augmented[k][k]
        assert pivot>0
        for i in range(k+1,d):
            factor = augmented[i][k]/pivot
            for j in range(k,d+1):
                augmented[i][j] -= factor*augmented[k][j]
    w = [F(0)]*d
    for i in range(d-1,-1,-1):
        w[i] = (augmented[i][-1]-sum(augmented[i][j]*w[j]
                 for j in range(i+1,d)))/augmented[i][i]
    b = ym-sum(m*v for m,v in zip(xm,w))
    return b,tuple(w)

X,y = [(-1,-1),(1,1)],[-2,2]
b,w = ridge_fit(X,y,2)
assert b==0 and w==(F(2,3),F(2,3))
assert ridge_fit([(-1,),(1,)],y,2)==(0,(F(1),))
assert ridge_fit([(-1,),(1,)],y,1)==(0,(F(4,3),))
assert ridge_fit([(8,8),(8,8)],[2,4],2)==(3,(0,0))
# Translating targets moves the unpenalized intercept, not the slopes.
assert ridge_fit(X,[8,12],2)==(10,w)
print("duplicate-column fit:",b,w)

For n rows and d features, forming the Gram matrix costs O(nd²), elimination O(d³), and centering O(nd). The implementation stores the design and working matrices, using O(nd+d²) scalar objects. Rational arithmetic has additional bit costs. When d is much larger than n, a dual formulation or iterative solver can avoid a d-by-d factorization; a tested numerical library should select a method appropriate to scale and conditioning.

There is a useful surprise in the assertions. If just one copy of the repeated feature is kept at the same λ=2, its slope is 1. That is not the sum 4/3 from the duplicated design. For a fixed combined slope s, splitting it equally over two copies gives penalty λ(s/2)2/2+λ(s/2)2/2=λs2/4\lambda(s/2)^2/2+\lambda(s/2)^2/2=\lambda s^2/4. The single-column problem would use λs2/2\lambda s^2/2. Duplication has halved the effective penalty on s. To match the duplicated model, use λ/2 for the merged feature. Equal coefficients on equal columns do not imply invariance to copying a column.

This calculation qualifies the fixed-λ interpretation of the identical-variable parenthetical in Hastie’s Section 2. The article’s algebra and exact example explicitly retain the changed penalty. A data preprocessing choice can alter the estimator even when it adds no new information.

Smaller variance can come with larger prediction error

With a fixed design Z and a centered linear model yc=Zw0+εcy_c=Zw_0+\varepsilon_c, assume E[εc]=0E[\varepsilon_c]=0 and Cov⁡(εc)=σ2C\operatorname{Cov}(\varepsilon_c)=\sigma^2C, where C=I−11⊤/nC=I-\mathbf1\mathbf1^\top/n is the centering matrix. Since CZ=ZCZ=Z, writing G=Z⊤ZG=Z^\top Z gives

E[w^λ]−w0=−λ(G+λI)−1w0,E[\widehat w_\lambda]-w_0=-\lambda(G+\lambda I)^{-1}w_0, Cov⁡(w^λ)=σ2(G+λI)−1G(G+λI)−1.\operatorname{Cov}(\widehat w_\lambda)=\sigma^2(G+\lambda I)^{-1}G(G+\lambda I)^{-1}.

These follow by substituting the estimator and applying linear expectation/covariance rules. Compared with full-column-rank OLS, the variance along a right-singular direction changes from σ2/dj2\sigma^2/d_j^2 to σ2dj2/(dj2+λ)2\sigma^2d_j^2/(d_j^2+\lambda)^2. It decreases, but bias can increase squared error. If observations follow a noiseless nonzero linear relationship, OLS can already predict perfectly and a positive penalty can make it worse. A general “ridge always improves accuracy” claim is false.

The penalty depends on feature units. Replacing a length in meters with centimeters divides its equivalent coefficient by one hundred and its squared penalty by ten thousand unless the penalty is adjusted. Training-fitted standardization is often useful, but it defines a particular penalty geometry. Do not fit scaling on held-out data. Select λ through validation or cross-validation and keep the final test set separate.

Ridge generally does not produce sparse coefficients and does not perform the same variable selection as Lasso. An intercept policy also matters: penalizing b would pull the baseline toward zero; this implementation leaves a constant-target fit unchanged. A Bayesian interpretation uses an explicit likelihood and prior scale, and a coefficient mode alone is not a predictive interval. See MAP for the role of loss scaling and posterior uncertainty.

For plain gradient descent, adding this quadratic penalty gives a multiplicative factor 1−ηλ1-\eta\lambda on w under the summed-loss convention. With momentum or adaptive optimizers, a setting named “weight decay” need not mean adding the same L2 term to the objective. D2L notes that this equivalence is optimizer-dependent; the linear ridge solution here is defined by J, not by an optimizer option’s name. D2L, Section 3.7.1

Check what the penalty actually touches

  1. For the duplicated two-observation design at λ=2, compare the ridge objective at (2/3,2/3) and (1,1). Answer: 4/3 and 2, respectively. The ridge optimum need not minimize training SSE by itself.
  2. Does removing one duplicate column at fixed λ preserve predictions? Answer: no. The total slope changes from 4/3 to 1 in the example. The merged problem needs λ/2 to preserve the duplicated model’s effective penalty.
  3. If an objective using summed squared loss has λ=6 and n=3, what coefficient belongs with averaged squared loss? Answer: 2, provided the entire objective is divided by three. Keeping six would strengthen regularization.
  4. What happens when every feature column is constant and the intercept is unpenalized? Answer: centered Z is zero, all penalized slopes are zero, and the intercept is the training target mean. The positive penalty still gives a unique slope vector.

Use the spectral view to ask better questions

The fitted-data matrix has factors dj2/(dj2+λ)d_j^2/(d_j^2+\lambda) instead of a hard keep/discard decision. Its trace is ∑jdj2/(dj2+λ)\sum_jd_j^2/(d_j^2+\lambda), a common effective-degrees-of-freedom measure for the centered fit; the unpenalized intercept adds one. This links ridge to principal-component regression and spectral regularization, while preserving their different treatment of directions.

A useful report records the penalty convention, intercept handling, feature scaling, λ-selection protocol, solver, and comparison baseline. Those choices make the result reproducible. They also explain why two packages can both implement ridge correctly and still give different coefficients when supplied with superficially identical settings.

Make a prediction, then check

After merging two identical columns, how do you preserve the original ridge penalty on their combined slope?

Choose one answer

Learning objectives

  • Derive centered ridge equations with an unpenalized intercept and SVD shrinkage, explaining positive definiteness and bias/variance.
  • Use exact solves to check how duplicated columns, feature units, λ scales and intercept policies change the estimator.

Prerequisites & connections

Explore related knowledge →

References

  1. Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
    Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020
  2. Dive into Deep Learning — 3.7 Weight Decay
    Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023
  3. Ridge Regularization: An Essential Concept in Data Science
    Trevor Hastie · 2020

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 every slope/intercept gradient and completed-square objective difference on exact random matrices; enumerated noise on an orthogonal design to verify SVD shrinkage and conditional variance.
  • Checked λ/k for one through five duplicated columns, translations, matching unit/λ scaling, constant targets and input boundaries; verified both 33-point coefficient curves against exact ridge solves.
  • Independent cross-review enumerated 16 ±1 noises on a nonorthogonal design, obtaining bias (−83/114,7/114) and covariance [[577,145],[145,577]]/9747, agreeing with the centered formulas; repeated observations with matching λ scaling were also checked.
  • The parent executed all 37 independent classical-method checks successfully; bilingual code, display equations, six main anchors and four answered exercises were individually compared.
  • After inspecting the desktop preview, added visible legend text for the blue fit and gray constant baseline; numerical values and coordinates are unchanged, and the component hash records the reviewed update.

Source locations checked:

  • Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft) · PDF306–307 (printed300–301), equations9.24–9.31: Gaussian-prior quadratic penalty and positive-definite diagonal shift. Intercept policy explicitly differs from penalizing all listed parameters.
  • Dive into Deep Learning — 3.7 Weight Decay · Section3.7.1, equations3.7.1–3.7.3, lines451–472; averaged loss convention, intercept policy and optimizer dependence of L2/weight-decay equivalence. No experiment curve or framework output copied.
  • Ridge Regularization: An Essential Concept in Data Science · Journal PDF1 metadata; Section1 PDF2 (printed426), equations1–3 and centering; Section2 PDF3 (printed427), equations9–10 SVD filters. PDF2 visually inspected. Fixed-λ claim about summed duplicate-column coefficients is qualified by an original exact counterexample and effective-penalty derivation; no blanket accuracy claim retained.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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