AI Wiki中文/EN

The kernel trick: an inner product with a geometry to check

核技巧

Relate explicit polynomial features to Gram matrices, prove kernel closure, reject an incompatible similarity and center new points with the training basis.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Compute the inner product without building every feature

A straight line in the original coordinates may be too restrictive. Adding squares and cross-products lets a linear model describe a curved relationship. But an expanded feature vector can become large. The kernel trick is an algebraic way to use some of those models while computing feature inner products directly.

Let phi map an input into a real inner-product space. A kernel returns the inner product in that space. If a model’s feature-space weight vector is a linear combination of training features, its score can be written entirely in kernel evaluations:

k(x,z)=⟨ϕ(x),ϕ(z)⟩,w=∑i=1nαiϕ(xi),f(z)=⟨w,ϕ(z)⟩=∑i=1nαik(xi,z).k(x,z)=\langle\phi(x),\phi(z)\rangle,\qquad w=\sum_{i=1}^{n}\alpha_i\phi(x_i),\qquad f(z)=\langle w,\phi(z)\rangle=\sum_{i=1}^{n}\alpha_i k(x_i,z).

The last equality is the trick: substitute the expansion for w and use linearity of the inner product. We still need a learning rule to choose the coefficients. This chapter supplies coefficients to check the representation; it does not claim to train a classifier by constructing a kernel matrix.

Algorithms that can be expressed using these inner products can often be rewritten in this form. An arbitrary algorithm that uses feature coordinates in other ways cannot be converted just by replacing one dot product. The Stanford notes demonstrate how the coefficient representation can remain closed under particular learning updates. CS229, §§1.1–1.3

A kernel needs compatible geometry for every finite set

Take a two-coordinate input x. For our concrete kernel, append a constant one and form all ordered products of the three coordinates. This deliberately redundant feature map has nine entries:

ϕ(x)=(1,x1,x2,x1,x12,x1x2,x2,x1x2,x22)⊤,ϕ(x)⊤ϕ(z)=(1+x1z1+x2z2)2.\phi(x)=(1,x_1,x_2,x_1,x_1^2,x_1x_2,x_2,x_1x_2,x_2^2)^\top,\qquad \phi(x)^\top\phi(z)=(1+x_1z_1+x_2z_2)^2.

To verify the identity, write u=(1,x_1,x_2) and v=(1,z_1,z_2). The dot product of the ordered-product vectors is the sum, over ordered pairs a,b, of u_a u_b v_a v_b. Factor the two sums to get the square of u’s dot product with v. Nothing is approximated. The repeated terms can be combined into six coordinates with suitable square-root-of-two factors; the nine-coordinate version keeps the independent computation rational.

For n inputs, the Gram matrix K contains all pairwise values, with entry K_ij=k(x_i,x_j). It must be symmetric and positive semidefinite (PSD). The reason is

c⊤Kc=∑i,jcicjk(xi,xj)=∥∑iciϕ(xi)∥2≥0for every c∈Rn.c^\top Kc=\sum_{i,j}c_i c_j k(x_i,x_j)=\left\|\sum_i c_i\phi(x_i)\right\|^2\ge 0\qquad\text{for every }c\in\mathbb R^n.

A real PSD kernel must satisfy this condition for every finite choice of inputs, including repeats, not only the training set we happen to have. Conversely, that symmetric finite-set condition guarantees an inner-product feature representation, possibly in an infinite-dimensional space. Some kernel literature calls this “positive definite”; it reserves “strictly positive definite” for the stronger no-zero-quadratic-form condition. We use “PSD” to avoid that naming ambiguity. Hofmann, Schölkopf and Smola, §2.2

Strict positivity or invertibility is not required. Repeated inputs give repeated Gram rows. For this polynomial kernel, the effective feature dimension is at most six, so a Gram matrix with more than six records is singular even if the records are distinct. It remains a valid kernel matrix.

Build new kernels through operations with a proof

On the same domain, nonnegative weighted sums of valid kernels remain valid: concatenate their feature maps after scaling by the square roots of the weights. Pointwise products remain valid: take all pairwise products of the feature coordinates, as in our polynomial example. Composing a kernel with the same input map on both arguments also preserves validity. So does multiplying by g(x)g(z) for any real-valued g, since the new feature map is g(x)phi(x). These constructions explain how to design a kernel without guessing a huge feature list. Kernel closure properties, Proposition 4

Arbitrary subtraction or an arbitrary transform of a similarity has no such guarantee. Symmetry, unit diagonal and entries between zero and one are insufficient. Consider three inputs in a chain, with neighboring similarity 9/10 and end-to-end similarity zero:

S=(19/1009/1019/1009/101),c=(1,−2,1)⊤,c⊤Sc=−65.S=\begin{pmatrix}1&9/10&0\\9/10&1&9/10\\0&9/10&1\end{pmatrix},\qquad c=(1,-2,1)^\top,\qquad c^\top Sc=-\frac65.

This negative value rules out any real inner-product feature map for those similarities. Each two-point principal block is individually PSD, yet the three points do not fit together. One counterexample disproves kernel validity; testing many sets without finding one does not prove validity over an unlimited domain.

Use the same training features for new points

We will compute Gram matrices and scores for the fixed kernel (1 + x dot z)**2. make_expansion stores a supplied training basis and coefficient vector. It does not optimize those coefficients or enforce the separate constraints that a particular learning algorithm might require. The matrix utility also accepts a different similarity function, allowing the invalid example to be examined. Merely accepting a callback does not certify it as a kernel.

Centering provides a useful consistency test. Suppose we subtract the mean of the training feature vectors from every feature vector, including future queries. For a query z and training point x_i, expanding that centered inner product gives

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_j k(z,x_j)-\frac1n\sum_j k(x_j,x_i)+\frac1{n^2}\sum_{j,l}k(x_j,x_l).

The two subtractions refer to the same training feature mean. In matrix form, training centering removes row and column means and adds the grand mean. A new query needs its mean similarity to the training basis, plus the stored training column means and grand mean. Centering each incoming query batch around its own mean would use a different feature map. A single query would then become the zero feature vector, changing its score merely because it was submitted alone.

The code fixes this convention in the expansion object. For n training points and m queries, query_kernel returns m rows and n columns. The coefficient vector always indexes the same stored training basis. Centering requires at least one training point. An uncentered empty expansion is allowed and represents the zero function.

from fractions import Fraction as F


def scalar(v):
    if isinstance(v,bool) or not isinstance(v,(int,F)):
        raise ValueError('values must be integers or Fractions')
    return F(v)


def points(rows):
    if not isinstance(rows,(list,tuple)):
        raise ValueError('points must be a list or tuple')
    out=[]
    for row in rows:
        if not isinstance(row,(list,tuple)) or len(row)!=2:
            raise ValueError('each point must have two coordinates')
        out.append(tuple(scalar(v) for v in row))
    return tuple(out)


def vector(values,length):
    if not isinstance(values,(list,tuple)) or len(values)!=length:
        raise ValueError('coefficient count must match the basis')
    return tuple(scalar(v) for v in values)


def quadratic(x,z):
    # Kernel callbacks receive validated pairs of rational coordinates.
    return (1+x[0]*z[0]+x[1]*z[1])**2


def tempting_similarity(x,z):
    if x==z:
        return F(1)
    return F(9,10) if x[1]==z[1] and abs(x[0]-z[0])==1 else F(0)


def kernel_matrix(left,right,kernel=quadratic):
    a,b=points(left),points(right)
    if not callable(kernel):
        raise ValueError('kernel must be callable')
    return tuple(tuple(scalar(kernel(x,z)) for z in b) for x in a)


def quadratic_form(matrix,coefficients):
    if not isinstance(matrix,(list,tuple)):
        raise ValueError('matrix must be a list or tuple')
    n=len(matrix)
    rows=tuple(vector(row,n) for row in matrix)
    c=vector(coefficients,n)
    if any(rows[i][j]!=rows[j][i] for i in range(n) for j in range(n)):
        raise ValueError('the Gram matrix must be symmetric')
    return sum((c[i]*rows[i][j]*c[j] for i in range(n) for j in range(n)),F(0))


def make_expansion(training,coefficients,center=False):
    # Coefficients are supplied; this function does not learn them.
    basis=points(training)
    alpha=vector(coefficients,len(basis))
    if type(center) is not bool:
        raise ValueError('center must be a bool')
    if center and not basis:
        raise ValueError('centering requires a nonempty training basis')
    means,grand=(),F(0)
    if center:
        gram=kernel_matrix(basis,basis)
        n=len(basis)
        means=tuple(sum(row,F(0))/n for row in gram)
        grand=sum(means,F(0))/n
    return {'basis':basis,'alpha':alpha,'center':center,
            'train_means':means,'grand_mean':grand}


def query_kernel(model,queries):
    # model must be an unmodified make_expansion result.
    rows=kernel_matrix(queries,model['basis'])
    if not model['center']:
        return rows
    n=len(model['basis'])
    out=[]
    for row in rows:
        query_mean=sum(row,F(0))/n
        out.append(tuple(v-query_mean-model['train_means'][j]+model['grand_mean']
                         for j,v in enumerate(row)))
    return tuple(out)


def scores(model,queries):
    return tuple(sum((v*a for v,a in zip(row,model['alpha'])),F(0))
                 for row in query_kernel(model,queries))


if __name__=='__main__':
    training=((0,0),(1,0),(0,1))
    alpha=(1,-2,1)
    queries=((1,1),(2,0))
    gram=kernel_matrix(training,training)
    model=make_expansion(training,alpha)
    centered=make_expansion(training,alpha,center=True)
    print('Gram:',tuple(tuple(str(v) for v in row) for row in gram))
    print('squared feature norm:',quadratic_form(gram,alpha))
    print('scores:',', '.join(map(str,scores(model,queries))))
    print('centered scores:',', '.join(map(str,scores(centered,queries))))
    print('centered training row sums:',tuple(sum(row) for row in query_kernel(centered,training)))
    chain=((0,0),(1,0),(2,0))
    bad=kernel_matrix(chain,chain,tempting_similarity)
    print('invalid similarity witness:',quadratic_form(bad,(1,-2,1)))
    empty=make_expansion((),())
    print('empty expansion:',scores(empty,queries))

The complete standard-library program prints:

Gram: (('1', '1', '1'), ('1', '4', '1'), ('1', '1', '4'))
squared feature norm: 15
scores: -3, -16
centered scores: -2, -15
centered training row sums: (Fraction(0, 1), Fraction(0, 1), Fraction(0, 1))
invalid similarity witness: -6/5
empty expansion: (Fraction(0, 1), Fraction(0, 1))

For the supplied coefficients, the feature-space weight has squared norm 15, as computed from the Gram matrix. Raw query scores −3 and −16 become −2 and −15 under the centered representation. Neither set is a probability. Centered training rows sum to zero because the centered training feature vectors sum to zero. The separate chain similarity gives the negative witness −6/5.

The program calculates a quadratic form for a supplied vector; it is not a general PSD-decision procedure. Positive values for selected vectors do not check all directions. Here kernel validity is established by the explicit feature construction, and invalidity by one negative witness. Independent explicit-feature calculations can verify both the raw and centered score identities without implementing a learning algorithm.

For the fixed two-coordinate kernel, constructing an m-by-n cross matrix takes O(1+m+n+mn) arithmetic/comparison operations and entries, including input validation and empty dimensions. Centered expansion preparation takes O(n²) time and temporary storage for nonempty n; the stored expansion itself has O(n) entries. Uncentered preparation takes O(1+n). Scoring has the same cross-matrix order because this simple implementation materializes that matrix. The symmetric quadratic-form utility takes O(1+n²) operations and storage. These counts exclude rational bit costs. Arbitrary callbacks have their own evaluation costs, and prediction assumes an unmodified expansion object.

Similarity, distance and predictive usefulness are different claims

PSD does not mean every kernel entry is nonnegative. The ordinary linear kernel can produce a negative dot product and still be valid. Nor does a large dot product necessarily mean two inputs are close: vector norms also contribute. Feature-space squared distance follows from

∥ϕ(x)−ϕ(z)∥2=k(x,x)+k(z,z)−2k(x,z).\|\phi(x)-\phi(z)\|^2=k(x,x)+k(z,z)-2k(x,z).

This expression is nonnegative for a valid kernel. Its square root is a distance between feature vectors, but can be only a pseudometric on inputs if different inputs share the same features. A generic kernel value is not itself a distance, probability or calibrated measure of relevance.

A valid kernel can still encode the wrong geometry for a task. Squared terms are sensitive to input scale. Any fitted normalization, feature selection or centering rule must be learned within the training protocol and then applied consistently to new inputs. A kernel parameter chosen using validation has also participated in model selection. Neither PSD nor an exact algebraic identity guarantees good performance on fresh data.

A finite Gram matrix by itself is also not a complete prediction rule for unseen inputs. It must be accompanied by a consistent way to calculate the cross matrix. Altering the training matrix, for example by changing its spectrum, does not automatically specify how a new point fits into the altered geometry. The extension must be defined, rather than mixing a modified training matrix with unrelated query similarities.

Finally, the kernel trick changes a computational tradeoff. It can avoid storing a very large feature vector, but a dense Gram matrix has n² entries. That may be expensive when the training sample is large. Our nine-coordinate example demonstrates an identity, not a speed advantage over an explicit six-coordinate polynomial implementation. Approximate features, sparse representations and specialized solvers address different parts of this tradeoff.

Test the geometry and the query convention

  1. For x=(1,0) and z=(0,1), compute the polynomial kernel and the dot product of their nine-coordinate features.

Answer: The raw dot product is zero, so the kernel is one. The expanded feature vectors share only their constant nonzero coordinate, giving the same dot product, one. Their self-kernel values are four, so their squared feature distance is 4+4−2=6.

  1. The chain similarity matrix is symmetric and has unit diagonal. What does the vector (1,−2,1) establish? Would its nonnegative two-point principal minors have been enough to approve it?

Answer: Its quadratic form is −6/5, which cannot be a squared feature norm, so the similarity is not a PSD kernel on these points. Every two-point principal minor is nonnegative, but the three-point determinant is −31/50. Pairwise checks missed an incompatible joint geometry.

  1. Why must a new query use the saved training feature mean, even when it is submitted alone? What happens if it is centered using only itself?

Answer: Centering is subtraction of a specified feature mean, not an index-exclusion rule. A new point must use the already chosen training mean, whether or not its coordinates equal a training point. Centering a single query around itself produces the zero vector and a zero centered linear score. In the main example, its correct training-centered score is −2, so changing the batch convention changes the model.

  1. A Gram matrix has duplicate rows and a nonzero coefficient vector with quadratic form zero. Must the kernel be invalid? Does checking one training Gram matrix prove a function is globally valid?

Answer: No to both. PSD permits zero quadratic forms; repeated feature vectors naturally produce them. For kernel validity over a domain, symmetry and PSD must hold for every finite input collection. One finite PSD matrix can represent those observed points, but cannot certify the function on every other point or define unseen cross values by itself.

From implicit features to function spaces

The computational idea is to preserve a model’s operations on inner products while changing the feature geometry those products represent. The coefficient form gives one concrete path from an explicit linear model to an implicit feature calculation. The Stanford notes develop that path before discussing kernel validity, making the distinction between a computational rewrite and a new learning objective clear. CS229 kernel methods

The broader mathematical theory relates symmetric PSD kernels to reproducing kernel Hilbert spaces. Hofmann, Schölkopf and Smola’s review connects this construction with kernel closure rules, examples and representer results for specified regularized optimization problems. Those results explain why finite kernel expansions arise in many learning methods; they do not say that any arbitrary objective automatically has such a solution. The review also distinguishes the general PSD formulation from the additional analytic assumptions associated with classical Mercer expansions. Kernel Methods in Machine Learning, §§2.2–2.3

Next, support vector machines add a margin objective and constraints; kernel ridge regression adds a particular regularized regression problem; and kernel PCA uses centered feature geometry for dimensionality reduction. Their shared kernel machinery does not make the objectives or fitted coefficients interchangeable. This chapter’s supplied coefficients isolate the common algebra so those later choices can be examined separately.

Make a prediction, then check

A similarity is symmetric, has unit diagonal and entries in [0,1]. Is this sufficient for kernel validity?

Choose one answer

Learning objectives

  • Rewrite an explicit feature-space linear score as a kernel expansion without confusing representation with coefficient fitting.
  • Prove PSD and closure using feature maps, and reject an apparently plausible similarity with a negative quadratic form.
  • Compute new-point cross kernels using the same training basis and saved training centering mean.

Prerequisites & connections

Explore related knowledge →

References

  1. CS229 Lecture Notes, Part V: Kernel Methods
    Andrew Ng; Tengyu Ma · 2019
  2. Kernel Methods in Machine Learning
    Thomas Hofmann; Bernhard Schölkopf; Alexander J. Smola · 2008

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.

  • Nine tests pass. An independent explicit nine-coordinate outer-product map verifies 100 kernel entries, three squared-norm identities and 12 raw/centered expansion reports with 48 query scores. Explicit feature-mean subtraction validates the cross-centering formula without reusing kernel mean subtraction.
  • Checked the −6/5 invalid-similarity witness and determinant −31/50 despite nonnegative pairwise principal minors, sum/product closure via explicit maps, negative entries in a valid linear kernel, singular repeated-input Gram matrices, query-batch invariance, basis/coefficient reordering, duplicate basis weights, empty uncentered expansion, rejected empty centering, invalid inputs and 80-digit coordinates.
  • Complete original bilingual prose, identical runnable Python and seven output lines, six matching display equations, six anchors and four answered exercises. Strict MDX/KaTeX/React HTML and MathML/emphasis checks pass using the shared rendering guard. Only article_text controls test article paths. Humanizer rereading completed. Status written means AI author checks; no human review, learned coefficient solver, general PSD decision procedure, whole-site build or browser acceptance.
  • 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:

  • CS229 Lecture Notes, Part V: Kernel Methods · Actually opened the official 30-page PDF. Cover gives Part V: Kernel Methods, Andrew Ng, updated by Tengyu Ma on April 21, 2019. Read §§1.1–1.3, printed pages 1–6: explicit features, coefficient-span preservation and prediction kernel expansion. §1.4, pages 6–10, contains polynomial products, Gram symmetry and the nonnegative quadratic-form argument. The article avoids treating a whole matrix-vector update as O(n), and uses the review’s careful distinction between general PSD kernels and classical Mercer conditions.
  • Kernel Methods in Machine Learning · Actually opened https://arxiv.org/pdf/math/0701907; header explicitly identifies math/0701907v3, July 1, 2008 and the 2008 journal record. Read §2.2, Definitions 1–3 (manuscript pages 4–5), RKHS construction and Moore–Aronszajn relation (pages 5–6), terminology paragraph and Proposition 4 (page 7), polynomial feature products (page 10), and §2.3.1 Theorem 9 (pages 16–17), including the strictly increasing norm penalty condition. Their positive definite means nonnegative quadratic form; this article calls that PSD. No source figure, experimental data or solver code reused. Centering is derived directly from the shared training feature mean.
  • CS229 Lecture Notes, Part V: Kernel Methods · Actually opened the exact university URL, a 30-page PDF; cover gives Andrew Ng and Tengyu Ma’s 21 April 2019 update. Read sections 1.1–1.3, pages 1–4, feature variables, zero-initialized update span and coefficient expansion; pages 8–10, Gram symmetry, nonnegative quadratic forms and finite-set validity. The article appropriately avoids the notes’ loose Mercer attribution and does not inherit an O(n) whole-matrix update claim. Extracted-text review, no visual or entire-course claim.
  • Kernel Methods in Machine Learning · Actually read https://arxiv.org/pdf/math/0701907, whose first page identifies v3, 1 July 2008, journal 36(3), 1171–1220 and distinct reprint pagination. Read definitions 1–3, manuscript pages 4–5, including strictly positive definite kernels being tested on distinct points; RKHS completion/Moore–Aronszajn and terminology, pages 5–7; Proposition 4 sum/product closure on page 7; Theorem 9 on pages 16–17, including strictly increasing norm penalty and the distinction from arbitrary objectives. Formula and terminology checks support the bounded exposition. No full-review-paper or image audit claim.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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