AI Wiki中文/EN

Kernel ridge regression: solve, center and predict

核岭回归

Derive the shifted Gram system, distinguish coefficient and function uniqueness, and fit an exact centered kernel model.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Choose the coefficients the kernel trick left open

A calibration table records responses 1, 3 and 3 at settings (0,0), (1,0) and (0,1). We want a smooth correction surface, not a rule that must reproduce every measurement. A polynomial kernel lets the surface bend; a ridge penalty controls the size of the fitted feature-space weight.

The kernel trick explains how to calculate a score once its coefficients are known. Kernel ridge regression (KRR) chooses those coefficients by minimizing squared error plus a squared-norm penalty. Its objective differs from the ε-insensitive loss used by support vector regression. Fixed scikit-learn 1.7.2 guide.

Our exact example fits the two-coordinate kernel k(x,z)=(1+x·z)². It includes a separate unpenalized intercept by default, using training-feature centering; that is an explicit option of this teaching implementation. It also offers the no-separate-intercept model. Neither setting learns a kernel or tunes its penalty automatically.

A positive diagonal shift gives a unique linear-system solution

First omit the separate intercept. Let phi be a feature map for a real PSD kernel. For positive rho, consider the summed-loss objective:

J(w)=∑i=1n(yi−⟨w,ϕ(xi)⟩)2+ρ∥w∥2,ρ>0.J(w)=\sum_{i=1}^n\left(y_i-\langle w,\phi(x_i)\rangle\right)^2+\rho\|w\|^2,\qquad \rho>0.

Any component of w orthogonal to the span of the training features changes no training predictions and only adds penalty. Thus the minimizer lies in that span. This is the elementary squared-loss case of the broader representer results discussed by Hofmann, Schölkopf and Smola. Their results require specified losses and norm penalties; the span conclusion is not automatic for arbitrary objectives. Review, section 2.3.1.

Write w as a sum of alpha_i phi(x_i), with Gram matrix K. One solution is obtained from:

(K+ρI)α=y,f^(z)=∑iαik(xi,z),c⊤(K+ρI)c≥ρ∥c∥2>0(c≠0). (K+\rho I)\alpha=y,\qquad \widehat f(z)=\sum_i\alpha_i k(x_i,z),\qquad c^\top(K+\rho I)c\ge\rho\|c\|^2>0\quad(c\ne0).

The inequality uses PSD of K and positive rho. It proves that the shifted system is positive definite and invertible, including when K is singular. Solve the system rather than explicitly forming its inverse.

Here is a direct optimality certificate. The equation gives residual vector r=y−K alpha=rho alpha. Consequently the feature-space gradient vanishes: the weighted sum of residual features equals rho w. For any feature-space perturbation v, expansion of the objective then cancels all cross terms:

J(w+v)−J(w)=∑i⟨v,ϕ(xi)⟩2+ρ∥v∥2.J(w+v)-J(w)=\sum_i\langle v,\phi(x_i)\rangle^2+\rho\|v\|^2.

This is nonnegative and strictly positive for nonzero v. The fitted weight is unique. The particular alpha returned by the shifted system is also unique, but these are different claims. If K has a null vector u, alpha+u represents the same weight and function; it minimizes the coefficient objective too, even though it does not solve the same shifted system. Differentiating the coefficient objective gives K[(K+rho I)alpha−y]=0. Cancelling a singular K would be invalid. Our shifted system gives a valid representative without that cancellation.

An unpenalized intercept needs a consistent centering rule

With a separate intercept b, minimize squared errors of y_i−b−⟨w,phi(x_i)⟩ plus rho times the squared norm. For fixed w, the best b is the training target mean minus the dot product of w with the training feature mean. Let H subtract the mean of an n-vector. Eliminating b gives:

H=I−1n11⊤,Kc=HKH,yc=Hy,(Kc+ρI)α=yc,f^(z)=yˉ+∑iαik~(z,xi).H=I-\frac1n\mathbf1\mathbf1^\top,\qquad K_c=HKH,\qquad y_c=Hy,\qquad (K_c+\rho I)\alpha=y_c,\qquad \widehat f(z)=\bar y+\sum_i\alpha_i\widetilde k(z,x_i).

The centered kernel uses phi(z) minus the saved training feature mean, even for unseen z. Its cross value is:

k~(z,xi)=k(z,xi)−1n∑jk(z,xj)−1n∑jk(xj,xi)+1n2∑j,lk(xj,xl).\widetilde k(z,x_i)=k(z,x_i)-\frac1n\sum_jk(z,x_j)-\frac1n\sum_jk(x_j,x_i)+\frac1{n^2}\sum_{j,l}k(x_j,x_l).

Because K_c has zero row and column sums and y_c sums to zero, the shifted solution’s coefficients sum to zero. This is a consequence of centering, not an additional arbitrary constraint. The same optimality argument applies after eliminating b; together with the uniquely minimizing b, it yields a unique fitted pair. Centering only the targets, or centering incoming queries around their own batch mean, does not implement this model.

State whether loss is summed or averaged

For the two objective conventions, the diagonal shift is:

∑iri2+λ∥w∥2 ⟹ ρ=λ,1n∑iri2+λ∥w∥2 ⟹ ρ=nλ.\sum_i r_i^2+\lambda\|w\|^2\ \Longrightarrow\ \rho=\lambda,\qquad \frac1n\sum_i r_i^2+\lambda\|w\|^2\ \Longrightarrow\ \rho=n\lambda.

Multiplying the averaged objective by n proves the second relation. Reusing the same numerical lambda under both conventions changes the fit. The program exposes average and reports effective_ridge; lambda is the user-facing penalty, while rho is what enters the system.

Fit, keep the training means, then answer new queries

The code accepts nonempty two-coordinate training points and aligned targets, all integers or Fraction. It rejects booleans and floats, requires a positive penalty and requires the two options to be actual booleans. Duplicated inputs and conflicting targets are allowed. The fixed polynomial kernel is PSD by its explicit feature construction.

solve_spd is an internal LDLᵀ factorization: L has unit diagonal, D contains positive pivots, and no square roots are needed. Forward substitution, division by D and backward substitution solve the system exactly. The helper assumes the symmetric matrix assembled by fit; it is not a general matrix-validation API. predict expects an unchanged fitted model and accepts an empty query list.

from fractions import Fraction as F


def scalar(x):
    if type(x) not in (int, F):
        raise ValueError('use integers or Fraction')
    return F(x)


def points(rows, empty=False):
    if type(rows) not in (list, tuple) or (not rows and not empty):
        raise ValueError('expected nonempty points')
    out = []
    for row in rows:
        if type(row) not in (list, tuple) or len(row) != 2:
            raise ValueError('each point has two coordinates')
        out.append(tuple(scalar(x) for x in row))
    return tuple(out)


def kernel(x, z):
    return (1+x[0]*z[0]+x[1]*z[1])**2


def solve_spd(matrix, rhs):
    # Internal exact LDL^T solve for the validated symmetric system.
    n = len(rhs)
    lower = [[F(i == j) for j in range(n)] for i in range(n)]
    diagonal = []
    for j in range(n):
        d = matrix[j][j]-sum((lower[j][k]**2*diagonal[k] for k in range(j)), F(0))
        if d <= 0:
            raise ValueError('system is not positive definite')
        diagonal.append(d)
        for i in range(j+1, n):
            lower[i][j] = (matrix[i][j]-sum((lower[i][k]*lower[j][k]*diagonal[k]
                                           for k in range(j)), F(0)))/d
    forward = []
    for i in range(n):
        forward.append(rhs[i]-sum((lower[i][j]*forward[j] for j in range(i)), F(0)))
    out = [F(0)]*n
    for i in reversed(range(n)):
        out[i] = forward[i]/diagonal[i]-sum((lower[j][i]*out[j] for j in range(i+1, n)), F(0))
    return tuple(out), tuple(diagonal)


def fit(training, targets, penalty=1, average=False, intercept=True):
    basis = points(training)
    if type(targets) not in (list, tuple) or len(targets) != len(basis):
        raise ValueError('one target per point required')
    y = tuple(scalar(v) for v in targets)
    penalty = scalar(penalty)
    if penalty <= 0 or type(average) is not bool or type(intercept) is not bool:
        raise ValueError('positive penalty and boolean options required')
    n = len(basis)
    ridge = penalty*n if average else penalty
    gram = tuple(tuple(kernel(x, z) for z in basis) for x in basis)
    means = tuple(sum(row, F(0))/n for row in gram) if intercept else (F(0),)*n
    grand = sum(means, F(0))/n
    offset = sum(y, F(0))/n if intercept else F(0)
    centered = tuple(tuple(gram[i][j]-means[i]-means[j]+grand for j in range(n))
                     for i in range(n))
    system = tuple(tuple(v+(ridge if i == j else 0) for j, v in enumerate(row))
                   for i, row in enumerate(centered))
    alpha, pivots = solve_spd(system, tuple(v-offset for v in y))
    predictions = tuple(offset+sum((v*a for v, a in zip(row, alpha)), F(0)) for row in centered)
    norm = sum((alpha[i]*centered[i][j]*alpha[j] for i in range(n) for j in range(n)), F(0))
    sse = sum(((v-p)**2 for v, p in zip(y, predictions)), F(0))
    assert all(v-p == ridge*a for v, p, a in zip(y, predictions, alpha))
    return {'basis': basis, 'alpha': alpha, 'intercept': intercept,
            'train_means': means, 'grand': grand, 'offset': offset,
            'effective_ridge': ridge, 'pivots': pivots, 'predictions': predictions,
            'norm_squared': norm, 'sse': sse,
            'objective': (sse/n if average else sse)+penalty*norm}


def predict(model, queries):
    queries = points(queries, empty=True)
    n = len(model['basis'])
    result = []
    for q in queries:
        row = tuple(kernel(q, x) for x in model['basis'])
        mean = sum(row, F(0))/n if model['intercept'] else F(0)
        result.append(model['offset']+sum(((v-mean-m+model['grand'])*a
                      for v, m, a in zip(row, model['train_means'], model['alpha'])), F(0)))
    return tuple(result)


if __name__ == '__main__':
    x, y = [(0, 0), (1, 0), (0, 1)], [1, 3, 3]
    model = fit(x, y)
    print('alpha:', tuple(map(str, model['alpha'])))
    print('training predictions:', tuple(map(str, model['predictions'])))
    print('norm / SSE / objective:', model['norm_squared'], model['sse'], model['objective'])
    print('new predictions:', tuple(map(str, predict(model, [(1, 1), (2, 0)]))))
    averaged = fit(x, y, average=True)
    equivalent = fit(x, y, penalty=3)
    print('mean-loss ridge / equivalent:', averaged['effective_ridge'], averaged['alpha'] == equivalent['alpha'])
    duplicate = fit([(0, 0), (0, 0)], [0, 2])
    print('duplicate alpha / predictions:', tuple(map(str, duplicate['alpha'])), tuple(map(str, duplicate['predictions'])))

Actual output:

alpha: ('-2/3', '1/3', '1/3')
training predictions: ('5/3', '8/3', '8/3')
norm / SSE / objective: 2/3 2/3 4/3
new predictions: ('11/3', '13/3')
mean-loss ridge / equivalent: 3 True
duplicate alpha / predictions: ('-1', '1') ('1', '1')

With penalty one and a separate intercept, the coefficients are (−2/3,1/3,1/3). Training predictions (5/3,8/3,8/3) deliberately stop short of interpolation. Their SSE is 2/3, the squared feature norm is 2/3, and the summed objective is 4/3. Every residual equals rho times its corresponding coefficient. The two new predictions are 11/3 and 13/3; they use no new labels and the same training mean.

At averaged-loss penalty one, rho becomes three. That gives the same coefficients as summed-loss penalty three, although the reported objective values differ by the factor n. The last example repeats exactly the same input with targets zero and two. No deterministic function can give that one input two answers. Both predictions are one; the centered Gram matrix is zero, but adding rho I makes the solve well defined. Its coefficients (−1,1) cancel in feature space.

For n records, fixed-dimensional kernel construction and centering take O(n²) operations. Dense LDLᵀ factorization takes O(n³); the remaining solves and diagnostics take O(n²). Working storage is O(n²), and the returned model uses O(n) entries because it need not retain the Gram matrix. Predicting m points takes O(1+m(n+1)) operations and O(n+m) extra slots, including an empty query. These count exact arithmetic/comparisons; numerator and denominator growth adds bit costs. Dense matrix storage and rational arithmetic limit the example to small datasets.

Well-defined fitting does not mean good prediction

A positive shift fixes invertibility; it does not certify that the kernel matches the task. Nor does it erase numerical issues in floating-point solvers when the shift is very small relative to the kernel’s scale. The exact rational demonstration avoids rounding to expose the equations, not to provide a scalable solver.

An unpenalized intercept and a constant coordinate inside a penalized kernel are different. With intercept=False, the constant feature of this polynomial kernel is part of w and receives the same norm penalty. With intercept=True, feature centering removes that constant direction from the penalized part, and the separate baseline is unpenalized. The difference is easy to miss when centering is treated as cosmetic preprocessing.

KRR generally lacks a mechanism that forces many expansion coefficients to zero. It can nevertheless have zero coefficients or redundant basis points; “typically dense” is not “every coefficient must be nonzero.” A full kernel expansion costs memory and new-point evaluations. Approximate features or low-rank methods change the computation and need their own approximation checks. KRR and SVR comparison.

Choose kernel settings and penalty using an appropriate validation procedure. Fit scaling and centering inside the training part of that procedure. Squared loss also gives large residuals substantial influence; a regularizer does not make the loss robust to arbitrary label errors. This program fixes its kernel and returns a training objective, not a generalization guarantee or a tuned production model.

Check the shift and the meaning of uniqueness

  1. There are three records. Which summed-loss penalty gives the same fit as averaged-loss penalty one?

Answer: Three. The averaged objective, multiplied by three, has summed SSE plus three times the squared norm. Thus both systems add 3I. Their minimizers coincide, but one objective is three times the other.

  1. Why is a singular Gram matrix not a reason to reject a positive-penalty KRR fit? Can alpha still have multiple equivalent representations?

Answer: For every nonzero c, cᵀ(K+rho I)c is at least rho times the squared norm of c and is strictly positive. The shifted system has one solution. A null vector of K may still be added to alpha without changing w or its function, so uniqueness of the chosen solve is not uniqueness of all coefficient representations.

  1. Two copies of the same input have targets zero and two. Under the default intercept model, why are both predictions one rather than zero and two?

Answer: A function must assign the same value to identical inputs. After centering their features, both are zero. The optimal unpenalized intercept is the target mean, one; the fitted penalized weight is zero. The returned coefficients (−1,1) cancel.

  1. A new point is submitted alone. Should the program subtract that point’s own feature vector to center it? What certificate checks the fitted training solve instead?

Answer: No. It must subtract the saved training feature mean. Self-centering would turn the query into a zero vector and change the prediction rule. For the fitted solve, every residual equals rho alpha_i; together with the PSD kernel this yields the nonnegative objective-increment identity and certifies optimality.

A finite system for a function-space problem

The representer perspective explains why a regularized problem in a potentially large feature space can have a finite training-point expansion. KRR makes the link especially transparent: squared loss yields a linear system, and the diagonal shift supplies strict positivity. The kernel-methods review places this case alongside more general norm-regularized objectives.

The next comparison is support vector regression. Its ε-insensitive loss introduces a flat region and constraints instead of this unconstrained quadratic solve. A shared kernel does not make the fitted coefficients interchangeable. Separately, compare primal and kernel ridge on an explicit polynomial feature map: they solve the same stated objective, but their matrix dimensions depend on feature count and sample count respectively.

Make a prediction, then check

For n training records, which diagonal shift matches mean squared loss plus lambda times the squared RKHS norm?

Choose one answer

Learning objectives

  • Prove positive definiteness after a positive diagonal shift and certify the fitted optimum.
  • Distinguish a unique shifted-system solution from nonunique coefficient representations of one function.
  • Apply training centering and the sum-versus-mean penalty convention consistently to predictions.

Prerequisites & connections

Explore related knowledge →

References

  1. Kernel Methods in Machine Learning
    Thomas Hofmann; Bernhard Schölkopf; Alexander J. Smola · 2008
  2. Kernel ridge regression — scikit-learn 1.7
    scikit-learn developers

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.

  • Six tests passed. Independent nine-feature primal regression solves by rational Gaussian elimination verify 16 centered/uncentered, summed/averaged models and 32 new-point predictions; 48 arbitrary feature/bias perturbations satisfy the exact global objective-increment certificate. The author kernel solve instead uses LDL factorization.
  • Checked singular duplicate inputs with conflicting targets, equivalent nullspace coefficients, positive pivots, exact n-lambda conversion, shrinkage, unpenalized versus penalized constants, query-batch and row-order consistency, empty queries, invalid inputs and preservation.
  • Complete original bilingual text, identical Python and six actual stdout lines, six displays, six stable anchors and four answered exercises. Strict MDX/KaTeX and actual React HTML passed; six mathematical annotations match. Humanizer reread, AI author checks only, written pending independent review. Draft only; no repository or library execution.
  • Ran all six author tests. Independently solved 12 small raw or bordered kernel systems by Cramer determinants using the permutation expansion, not LDL or the author test’s explicit-feature Gaussian elimination. The bordered system uses raw Gram entries and an unpenalized intercept equation, avoiding the implemented centering procedure. All coefficients, 36 new-point predictions, norms and 12 squared-loss Fenchel primal-dual equalities agree.
  • Reviewed singular duplicate inputs with conflicting targets, constant and one-record data, centered/uncentered fits and averaged/summed normalization. Verified rho=n*lambda for average loss, unique feature weight versus nullspace coefficient freedom, sum-zero centered representative, saved-training-mean cross prediction and the distinction between the returned target-mean offset and the raw-feature intercept. Dense time/storage and rational bit-cost qualifications are consistent.
  • Read complete English and Chinese articles, executable code, exercises and metadata. Strict MDX/KaTeX with actual React HTML passes: six displays, six anchors and four answers per language; all six math annotations match. The executable fence equals example.py, and author tests verify the identical bilingual code and six stdout lines. Five hashes and all source identities/URLs match the frozen metadata. No changes requested.
  • 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.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

  • Kernel Methods in Machine Learning · Reuses the exact source identity and URL from kernel-trick. Actually read the arXiv v3 PDF (header 1 July 2008), definitions 1–3 and RKHS construction on manuscript pages 4–7, plus section 2.3.1 Theorem 9 on pages 16–17: loss depending on sample evaluations, strictly increasing norm penalty and finite expansion. This chapter independently derives the squared-loss shifted system and its objective-increment certificate; it does not cancel a singular Gram matrix or assert arbitrary-objective representer results.
  • Kernel ridge regression — scikit-learn 1.7 · Actually opened /1.7/modules/kernel_ridge.html, rendered 1.7.2, lines 69–77. Read squared loss versus epsilon-insensitive SVR, L2 regularization, feature-space linearity and expansion sparsity discussion. Do not generalize its dataset-specific speed comparisons or absolute sparsity wording. The separate generated API URL failed to open, so it is not counted as a source; no library execution or API-default intercept equivalence claimed.
  • Kernel Methods in Machine Learning · Actually opened https://arxiv.org/pdf/math/0701907v3, 53-page electronic reprint. Read the first-page 1 July 2008 v3 header and Annals 36(3), 1171–1220 identity; Definitions 1–3 on manuscript pages 4–5 distinguish semidefinite from strict definiteness, and section 2.3.1/Theorem 9 on pages 16–17 requires an evaluation-dependent loss and strictly increasing norm penalty for every minimizer to have a finite expansion. The chapter supplies its own squared-loss optimality proof and does not cancel singular K. Metadata canonical abs URL retained exactly. No whole-paper visual audit.
  • Kernel ridge regression — scikit-learn 1.7 · Actually opened the fixed 1.7 guide, rendered 1.7.2, lines 69–75: feature-space linearity, squared versus epsilon-insensitive loss, L2 regularization and sparsity discussion. The chapter correctly qualifies typical density rather than adopting the page’s absolute non-sparse statement, and does not reproduce its dataset-specific speed comparisons. No generated API or library execution was needed for this review.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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