Module contents
Lesson 13 of 24Core 105 min

Kernels: nonlinear SVMs, support vector regression and Nyström

Generalize linear models to feature spaces of arbitrary dimension with the kernel trick. Recognize and construct valid kernels, apply the trick to SVM and support vector regression, and address quadratic or cubic cost in n with the Nyström approximation. RKHS theory, the representer theorem, kernel ridge and random Fourier features are developed in m13.

After this lesson you can

  • Verify that the polynomial kernel corresponds to an explicit inner product and calculate feature-space dimension.
  • Kernelize an algorithm using only inner products, such as the centroid classifier or SVM dual, computing feature-space distances using the kernel.
  • Numerically check whether a similarity is a valid kernel and construct new kernels with closure rules.
  • Fit RBF-kernel SVM and SVR and reason about the joint roles of C, γ and ε.
  • Implement the Nyström approximation and measure Gram-matrix error, accuracy and time against the exact kernel.

Before you start

Motivation: curved boundaries without constructing φ

The previous lesson’s SVM seeks the widest soft-margin hyperplane. If classes form two concentric rings, no plane hyperplane works: every line leaves half of each ring on the wrong side. The classical recipe is familiar from basis-function expansion: transform each x\vb{x} with map ϕ\phi into a larger feature space and fit a linear model there. With ϕ(x)=(x1,x2,x12+x22)\phi(\vb{x}) = (x_1, x_2, x_1^2 + x_2^2), rings lie at different heights and a horizontal plane separates them; back in the plane that hyperplane is a circle.

The problem is the size of ϕ\phi. All monomials through degree 3 of a vector in R100\R^{100} have 176 851 coordinates; through degree 5 of an MNIST image (d=784d = 784), about 2.5×10122.5 \times 10^{12}. Explicitly constructing ϕ(x)\phi(\vb{x}) quickly becomes impossible. The saving observation is that many algorithms never inspect coordinates of ϕ(x)\phi(\vb{x}): they use only inner products ϕ(x)⊤ϕ(z)\phi(\vb{x})\T\phi(\vb{z}). For certain ϕ\phi this product takes O(d)\bigO(d) operations via a closed formula k(x,z)k(\vb{x}, \vb{z}) without visiting coordinates. The Gaussian kernel even has an infinite-dimensional feature space while computation still costs the same.

A second reason is equally important in practice. If the algorithm only needs kk, data need not be vectors. A similarity function behaving like an inner product suffices:

  • Strings. The spectrum kernel counts shared length-qq fragments of two sequences: k(s,t)=∑ucu(s) cu(t)k(s, t) = \sum_{u} c_u(s)\,c_u(t), with cu(s)c_u(s) the number of occurrences of fragment uu in ss. It was used to classify proteins with SVM (Leslie, Eskin and Noble, 2002); you will use it on DNA at the lesson’s end.
  • Sets. k(A,B)=∣A∩B∣k(A, B) = \abs{A \cap B} is the inner product of indicator vectors of AA and BB.
  • Graphs. Weisfeiler–Lehman kernels compare graphs by shared labeled subtrees; you will study them as graph kernels.

This lesson turns that observation into a tool: what the kernel trick is and which algorithms admit it, how to tell if a similarity is a valid kernel and build new kernels, why the Gaussian kernel dominates practice, kernelized SVM and support vector regression, joint hyperparameter selection, and avoiding quadratic cost in nn with the Nyström approximation. Background theory (reproducing-kernel Hilbert spaces, representer theorem, kernel ridge and random Fourier features) is in m13.

Intuition: lifting data to separate them

InteractiveLifting data to separate them
  • class +1 (inner ring)
  • class −1 (outer ring)
  • plane z=hz = h and its circle
Feature space
Lifting
1.00
1.45
Accuracy of plane z=hz = h100.0 %
Radius of projected circle h/t\sqrt{h/t}1.20
Dimensionfrom 2 to 3
The plane z=1.45z = 1.45 separates both classes; below, its intersection with the surface projects to the circle t (x12+x22)=ht\,(x_1^2 + x_2^2) = h, with radius 1.20.
Two rings (explicit model: radii 0.76 and 1.68 with Gaussian noise 0.14) lifted with ϕ(x)=(x1,x2,x12+x22)\phi(\vb{x}) = (x_1, x_2, x_1^2 + x_2^2). Rotate the scene. Lower lift tt to 0: points return to the plane and no plane separates them. Increase it: plane z=hz = h leaves one ring above and one below, and its intersection with the paraboloid projects to the dashed circle. Switch to ‘Grado 2 completo’ (full degree 2): an SVM with k(x,z)=(x⊤z+1)2k(\vb{x}, \vb{z}) = (\vb{x}\T\vb{z} + 1)^2 is a hyperplane in a 6-coordinate space that cannot be drawn; the scene shows what it sees, height f(x)=w⊤ϕ(x)+bf(\vb{x}) = \vb{w}\T\phi(\vb{x}) + b, and its intersection with z=0z = 0, a conic. What conic appears for ‘Signo de x1x2x_1x_2’ data?

For the ‘Signo de x1x2x_1x_2’ data, the ideal boundary is the pair of lines x1x2=0x_1x_2 = 0, a degenerate conic; SVM finds a nearby hyperbola (B2−4AC>0B^2 - 4AC > 0), possible only because ϕ\phi includes coordinate x1x2x_1x_2. Two more lessons from the figure. First, a classifier linear in ϕ\phi space has, in the original space, boundary level set {x:w⊤ϕ(x)+b=0}\{\vb{x} : \vb{w}\T\phi(\vb{x}) + b = 0\}. With quadratic ϕ\phi, a conic; cubic ϕ\phi, a cubic; Gaussian kernel, almost any curve. Second, in degree-2 mode the ‘k(x1,x2)k(\vb{x}_1, \vb{x}_2) and ϕ(x1)⊤ϕ(x2)\phi(\vb{x}_1)\T\phi(\vb{x}_2)’ readout gives the same number, but SVM never built ϕ\phi: it worked only with kk. Explicit ϕ\phi is used only for drawing.

The kernel trick

Matrix K∈Rn×n\mat{K} \in \R^{n\times n} with Kij=k(xi,xj)K_{ij} = k(\vb{x}_i, \vb{x}_j) is the data Gram matrix. A kernelized algorithm sees only K\mat{K} in training and vectors (k(x1,x),…,k(xn,x))\big(k(\vb{x}_1, \vb{x}), \dots, k(\vb{x}_n, \vb{x})\big) when predicting. Which admit this? Those writable using inner products whose solution is a linear combination of ϕ(xi)\phi(\vb{x}_i): SVM dual, perceptron, ridge (kernel ridge, m13), PCA (kernel PCA), k-nearest neighbors with feature-space distance, and the centroid classifier below. That the solution lies in the span of ϕ(xi)\phi(\vb{x}_i) is no accident: for every empirical-loss minimization plus an increasing penalty on ∥w∥\norm{\vb{w}}, the representer theorem guarantees it.

The polynomial kernel, coordinate by coordinate

In R2\R^2, expand (x⊤z)2(\vb{x}\T\vb{z})^2:

(x1z1+x2z2)2=x12z12+2x1x2z1z2+x22z22=ϕ(x)⊤ϕ(z),ϕ(x)=(x12, 2 x1x2, x22).(x_1z_1 + x_2z_2)^2 = x_1^2z_1^2 + 2x_1x_2z_1z_2 + x_2^2z_2^2 = \phi(\vb{x})\T\phi(\vb{z}), \qquad \phi(\vb{x}) = (x_1^2,\ \sqrt{2}\,x_1x_2,\ x_2^2).

The 2\sqrt 2 is essential: the cross term appears twice in the expansion and its weight is shared between ϕ(x)\phi(\vb{x}) and ϕ(z)\phi(\vb{z}). The same argument works generally using the multinomial theorem.

Proof

x⊤z+c=∑j=0dx~jz~j\vb{x}\T\vb{z} + c = \sum_{j=0}^d \tilde{x}_j\tilde{z}_j. By the multinomial theorem, (∑jaj)p=∑∣m∣=pp!m!∏jajmj\big(\sum_j a_j\big)^p = \sum_{\abs{\vb{m}} = p} \frac{p!}{\vb{m}!}\prod_j a_j^{m_j}, with m!=∏jmj!\vb{m}! = \prod_j m_j!. With aj=x~jz~ja_j = \tilde{x}_j\tilde{z}_j, each summand is p!m!∏jx~jmj∏jz~jmj=ϕm(x) ϕm(z)\frac{p!}{\vb{m}!}\prod_j\tilde{x}_j^{m_j}\prod_j\tilde{z}_j^{m_j} = \phi_{\vb{m}}(\vb{x})\,\phi_{\vb{m}}(\vb{z}). The number of vectors m∈Nd+1\vb{m} \in \N^{d+1} summing to pp equals the ways of distributing pp balls among d+1d + 1 boxes, (p+dd)=(d+pp)\binom{p + d}{d} = \binom{d + p}{p} (stars and bars). If c=0c = 0, x~0=0\tilde{x}_0 = 0 cancels every term with m0>0m_0 > 0, leaving distributions of pp balls among dd boxes.

∎

Coordinates of ϕ\phi are, up to weights, all monomials of degree at most pp in x1,…,xdx_1, \dots, x_d. Constant cc controls relative degree weights: a degree-qq monomial has factor c(p−q)/2c^{(p-q)/2}, so large cc favors lower degrees. Computing kk costs O(d)\bigO(d); computing ϕ(x)⊤ϕ(z)\phi(\vb{x})\T\phi(\vb{z}) explicitly costs O((d+pp))\bigO\big(\binom{d+p}{p}\big).

Distances and centroids in feature space

The trick is not limited to inner products: anything expressed with them can be computed. Distance, for example:

∥ϕ(x)−ϕ(z)∥2=k(x,x)−2k(x,z)+k(z,z).\norm{\phi(\vb{x}) - \phi(\vb{z})}^2 = k(\vb{x}, \vb{x}) - 2k(\vb{x}, \vb{z}) + k(\vb{z}, \vb{z}).

This kernelizes distance-based methods. The simplest example, used by Schölkopf and Smola in chapter 1 of Learning with Kernels, is the centroid classifier: assign x\vb{x} to the class with nearest centroid μc=1nc∑i:yi=cϕ(xi)\vb{\mu}_c = \frac{1}{n_c}\sum_{i : y_i = c}\phi(\vb{x}_i). The centroid lives in H\mathcal{H} and need not be constructed because inner-product linearity gives

∥ϕ(x)−μc∥2=k(x,x)−2nc∑i:yi=ck(x,xi)+1nc2∑i,j:yi=yj=ck(xi,xj).\norm{\phi(\vb{x}) - \vb{\mu}_c}^2 = k(\vb{x}, \vb{x}) - \frac{2}{n_c}\sum_{i : y_i = c} k(\vb{x}, \vb{x}_i) + \frac{1}{n_c^2}\sum_{i, j : y_i = y_j = c} k(\vb{x}_i, \vb{x}_j).

The first term is common to both classes and cancels in comparison. The remainder has a clear interpretation: the rule compares x\vb{x}’s average similarity to each class, corrected for class “cohesion,” ∥μc∥2\norm{\vb{\mu}_c}^2. Subtracting distances gives rule sign⁡(f(x))\operatorname{sign}(f(\vb{x})) with

f(x)=2n+∑yi=+1k(x,xi)−2n−∑yi=−1k(x,xi)+∥μ−∥2−∥μ+∥2=⟨w,ϕ(x)⟩+b,f(\vb{x}) = \frac{2}{n_+}\sum_{y_i = +1} k(\vb{x}, \vb{x}_i) - \frac{2}{n_-}\sum_{y_i = -1} k(\vb{x}, \vb{x}_i) + \norm{\vb{\mu}_-}^2 - \norm{\vb{\mu}_+}^2 = \inner{\vb{w}}{\phi(\vb{x})} + b,

with w=2(μ+−μ−)\vb{w} = 2(\vb{\mu}_+ - \vb{\mu}_-): a linear classifier in H\mathcal{H} whose weight vector is a combination of ϕ(xi)\phi(\vb{x}_i) with coefficients ±2/nc\pm 2/n_c. With a Gaussian kernel, 1nc∑ik(x,xi)\frac{1}{n_c}\sum_i k(\vb{x}, \vb{x}_i) is, up to a constant, a kernel density estimate of class cc: the classifier compares estimated densities with correction ∥μ−∥2−∥μ+∥2\norm{\vb{\mu}_-}^2 - \norm{\vb{\mu}_+}^2, penalizing the more concentrated class. Every training point enters ff; as you will see, SVM keeps only a few.

A warning the final guided exercise will check: centroid μc\vb{\mu}_c is not the image of the data mean, ϕ(1nc∑ixi)\phi\big(\frac{1}{n_c}\sum_i\vb{x}_i\big), unless ϕ\phi is linear. Generally there may not even be an x\vb{x} with ϕ(x)=μc\phi(\vb{x}) = \vb{\mu}_c (the preimage problem).

From scratch: polynomial kernel and centroid classifier

The first cell constructs the theorem’s explicit ϕ\phi with combinations_with_replacement (each combination of indices from {0,…,d}\{0, \dots, d\} with repetition is an m\vb{m}), checks it reproduces the kernel, and measures cost.

[ ]The polynomial kernel is an inner productBrowser
import time
import numpy as np
from itertools import combinations_with_replacement
from math import comb, factorial

def phi_poly(X, p, c=1.0):
    """φ explícita de k(x, z) = (xᵀz + c)^p: todos los monomios de grado p de (√c, x₁, ..., x_d),
    cada uno con la raíz de su coeficiente multinomial."""
    n, d = X.shape
    Xa = np.hstack([np.full((n, 1), np.sqrt(c)), X])
    cols = []
    for idx in combinations_with_replacement(range(d + 1), p):
        m = np.bincount(idx, minlength=d + 1)                # el multiíndice m
        multinom = factorial(p) // int(np.prod([factorial(int(v)) for v in m]))
        cols.append(np.sqrt(multinom) * np.prod(Xa[:, list(idx)], axis=1))
    return np.column_stack(cols)

rng = np.random.default_rng(0)
X = rng.normal(size=(5, 2))
F = phi_poly(X, p=2, c=1.0)
print("d = 2, p = 2: φ tiene", F.shape[1], "coordenadas;",
      "max |φ(x)ᵀφ(z) − (xᵀz + 1)²| =", f"{np.abs(F @ F.T - (X @ X.T + 1) ** 2).max():.1e}")

X = rng.normal(size=(200, 10))
F = phi_poly(X, p=3, c=1.0)
print("d = 10, p = 3:", F.shape[1], "coordenadas; C(13, 3) =", comb(13, 3),
      "; error relativo máximo", f"{np.abs(F @ F.T - (X @ X.T + 1) ** 3).max() / np.abs((X @ X.T + 1) ** 3).max():.1e}")

print("\ndimensión de φ para (xᵀz + c)^p con c > 0: C(d + p, p)")
print("     d     p = 2       p = 3            p = 5")
for d in [2, 10, 100, 784]:
    print(f"{d:6d} {comb(d + 2, 2):9d} {comb(d + 3, 3):11d} {comb(d + 5, 5):16d}")

X = rng.normal(size=(300, 30))
t = time.perf_counter(); F = phi_poly(X, p=3); G1 = F @ F.T; t_phi = time.perf_counter() - t
t = time.perf_counter(); G2 = (X @ X.T + 1) ** 3; t_k = time.perf_counter() - t
print(f"\nd = 30, p = 3, n = 300: φ con {F.shape[1]} coordenadas. "
      f"Gram por φ: {t_phi * 1e3:.0f} ms; por el kernel: {t_k * 1e3:.1f} ms; iguales: {np.allclose(G1, G2)}")

The table motivates the trick: with d=100d = 100 and p=3p = 3, ϕ\phi already has 176 851 coordinates, and with d=784d = 784 and p=5p = 5, more than two trillion. For d=30d = 30, p=3p = 3 and 300 points, explicit Gram construction (5456 coordinates) is about a hundred times slower than by kernel in the browser (exact ratio depends on machine), and the difference grows like (d+pp)/d\binom{d + p}{p}/d.

The second cell implements common kernels vectorized (no loops, using identity ∥a−b∥2=∥a∥2+∥b∥2−2a⊤b\norm{\vb{a} - \vb{b}}^2 = \norm{\vb{a}}^2 + \norm{\vb{b}}^2 - 2\vb{a}\T\vb{b}) and the centroid classifier using only kernel evaluations, testing it on concentric rings.

[ ]Vectorized kernels and kernel centroid classifierBrowser
import numpy as np

def sqdist(A, B):
    """Distancias euclídeas al cuadrado entre las filas de A y las de B, sin bucles."""
    d2 = (A ** 2).sum(1)[:, None] + (B ** 2).sum(1)[None, :] - 2 * A @ B.T
    return np.maximum(d2, 0.0)                   # el redondeo puede dar −1e−16

def k_lineal(A, B):
    return A @ B.T

def k_poly(A, B, p=2, c=1.0):
    return (A @ B.T + c) ** p

def k_rbf(A, B, gamma=1.0):
    return np.exp(-gamma * sqdist(A, B))

def k_laplace(A, B, gamma=1.0):
    """El laplaciano de scikit-learn: exp(−γ‖x − z‖₁)."""
    return np.exp(-gamma * np.abs(A[:, None, :] - B[None, :, :]).sum(-1))

def anillos(n, rng):
    c = np.where(np.arange(n) % 2 == 0, 1, -1)
    r = np.where(c == 1, 0.95, 2.1) + 0.17 * rng.normal(size=n)
    th = rng.uniform(0, 2 * np.pi, n)
    return np.c_[r * np.cos(th), r * np.sin(th)], c

class CentroideKernel:
    """Asigna x a la clase de centroide más próximo en el espacio de características, solo con k."""
    def __init__(self, kernel):
        self.kernel = kernel
    def fit(self, X, y):
        self.X, self.y = X, y
        self.norma2 = {c: self.kernel(X[y == c], X[y == c]).mean() for c in (-1, 1)}   # ‖μ_c‖²
        return self
    def dist2(self, Xq, c):
        """‖φ(x) − μ_c‖² = k(x, x) − (2/n_c) Σ_i k(x, x_i) + ‖μ_c‖²."""
        kxx = np.array([self.kernel(x[None], x[None])[0, 0] for x in Xq])
        return kxx - 2 * self.kernel(Xq, self.X[self.y == c]).mean(1) + self.norma2[c]
    def predict(self, Xq):
        return np.where(self.dist2(Xq, 1) < self.dist2(Xq, -1), 1, -1)

rng = np.random.default_rng(1)
Xtr, ytr = anillos(300, rng)
Xte, yte = anillos(1000, rng)
for nombre, k in [("lineal", k_lineal), ("polinómico p = 2", k_poly),
                  ("RBF γ = 1", k_rbf), ("laplaciano γ = 1", k_laplace)]:
    acc = (CentroideKernel(k).fit(Xtr, ytr).predict(Xte) == yte).mean()
    print(f"centroide con kernel {nombre:17s} exactitud de prueba {acc:.3f}")

# la distancia por el kernel es la distancia entre los φ explícitos de la celda anterior
x, z = Xtr[:1], Xtr[1:2]
Fx, Fz = phi_poly(x, 2), phi_poly(z, 2)
print("\n‖φ(x) − φ(z)‖²: explícita", round(float(((Fx - Fz) ** 2).sum()), 10),
      "  con el kernel", round((k_poly(x, x) + k_poly(z, z) - 2 * k_poly(x, z)).item(), 10))

With the linear kernel both centroids are nearly at the origin (rings are symmetric) and accuracy is 52.6 %, virtually random. A degree-2 polynomial kernel whose space contains x12+x22x_1^2 + x_2^2 reaches 98.1 %, and RBF or Laplacian reaches 99.8 %. The algorithm is identical in all four rows; only kk changed.

Valid kernels in practice

Not every two-argument function is a kernel. Checking the definition requires finding ϕ\phi, not always easy. Fortunately a criterion examines only finite matrices.

Proof

The first part is one line: c⊤Kc=∑i,jcicj⟨ϕ(xi),ϕ(xj)⟩=∥∑iciϕ(xi)∥2≥0\vb{c}\T\mat{K}\vb{c} = \sum_{i,j}c_ic_j\inner{\phi(\vb{x}_i)}{\phi(\vb{x}_j)} = \norm{\sum_i c_i\phi(\vb{x}_i)}^2 \ge 0. The general converse (Moore–Aronszajn construction of a reproducing-kernel Hilbert space) starts RKHS. On finitely many points it is immediate and enough in practice: if K=UΛU⊤\mat{K} = \mat{U}\mat{\Lambda}\mat{U}\T is positive semidefinite, by the spectral theorem vectors ϕ(xi)=Λ1/2U⊤ei∈Rn\phi(\vb{x}_i) = \mat{\Lambda}^{1/2}\mat{U}\T\vb{e}_i \in \R^n satisfy ϕ(xi)⊤ϕ(xj)=(UΛU⊤)ij=Kij\phi(\vb{x}_i)\T\phi(\vb{x}_j) = (\mat{U}\mat{\Lambda}\mat{U}\T)_{ij} = K_{ij}.

∎

The practical test: generate points, compute the Gram matrix and inspect its minimum eigenvalue. One λmin⁡<0\lambda_{\min} < 0 (clearly beyond rounding) certifies kk is not a kernel: if c\vb{c} is its eigenvector, c⊤Kc=λmin⁡<0\vb{c}\T\mat{K}\vb{c} = \lambda_{\min} < 0, which would be the squared norm of ∑iciϕ(xi)\sum_i c_i\phi(\vb{x}_i). Nonnegative eigenvalues on a few datasets prove nothing but are encouraging. Rounding needs attention: in float64 a nearly singular positive-semidefinite Gram matrix (RBF with small γ\gamma, or low-rank polynomial) gives eigenvalues on the order of −10−16λmax⁡-10^{-16}\lambda_{\max}, and tolerance should be relative to λmax⁡\lambda_{\max}. For the same reason Cholesky factorization of a Gram matrix often fails and a little diagonal jitter is added.

Construction rules

Kernel validity is almost never proved from scratch: build from others with rules preserving positive semidefiniteness.

Proof

Using feature maps ϕ1,ϕ2\phi_1, \phi_2: (1) concatenate, ϕ=(ϕ1,ϕ2)\phi = (\phi_1, \phi_2). (2) ϕ=a ϕ1\phi = \sqrt{a}\,\phi_1. (3) Tensor product: ϕ(x)=ϕ1(x)⊗ϕ2(x)\phi(\vb{x}) = \phi_1(\vb{x})\otimes\phi_2(\vb{x}), with coordinates all products ϕ1,a(x)ϕ2,b(x)\phi_{1,a}(\vb{x})\phi_{2,b}(\vb{x}), satisfies ⟨ϕ(x),ϕ(z)⟩=∑a,bϕ1,a(x)ϕ1,a(z)ϕ2,b(x)ϕ2,b(z)=k1(x,z)k2(x,z)\inner{\phi(\vb{x})}{\phi(\vb{z})} = \sum_{a,b}\phi_{1,a}(\vb{x})\phi_{1,a}(\vb{z})\phi_{2,b}(\vb{x})\phi_{2,b}(\vb{z}) = k_1(\vb{x}, \vb{z})k_2(\vb{x}, \vb{z}) (in matrix terms, the Schur product theorem: elementwise product of two positive-semidefinite matrices is positive semidefinite). (4) ϕ=f\phi = f, valued in R\R. (5) ϕ=ϕ1∘g\phi = \phi_1\circ g. (6) Induct using (1), (2), (3), plus constant a0=(a0)2a_0 = (\sqrt{a_0})^2, which is (4) with constant ff. (7) exp⁡(k1)=lim⁡N∑j≤Nk1j/j!\exp(k_1) = \lim_N\sum_{j \le N}k_1^j/j!; each partial sum is a kernel by (6), and if c⊤KNc≥0\vb{c}\T\mat{K}_N\vb{c} \ge 0 for every NN, the limit is also ≥0\ge 0. (8) Apply (3) to k1k_1 and the kernel from (4) with f(x)=k1(x,x)−1/2f(\vb{x}) = k_1(\vb{x}, \vb{x})^{-1/2}; geometrically ϕ1(x)/∥ϕ1(x)∥\phi_1(\vb{x})/\norm{\phi_1(\vb{x})}.

∎

These rules produce the most used kernel. Expand squared distance:

e−γ∥x−z∥2=e−γ∥x∥2 e−γ∥z∥2 e2γx⊤z.e^{-\gamma\norm{\vb{x} - \vb{z}}^2} = e^{-\gamma\norm{\vb{x}}^2}\, e^{-\gamma\norm{\vb{z}}^2}\, e^{2\gamma\vb{x}\T\vb{z}}.

The last factor is an exponential of a scaled linear kernel (rules 2 and 7), and the first two are f(x)f(z)f(\vb{x})f(\vb{z}) with f(x)=e−γ∥x∥2f(\vb{x}) = e^{-\gamma\norm{\vb{x}}^2} (rule 4); the product is a kernel by rule 3. In fact it is exactly the normalization (rule 8) of e2γx⊤ze^{2\gamma\vb{x}\T\vb{z}}.

These are common kernels and their construction rules, with each similarity’s meaning:

Kernelk(x,z)k(\vb{x}, \vb{z})ParametersWhat it measures
Linearx⊤z\vb{x}\T\vb{z}the usual linear model
Polynomial(x⊤z+c)p(\vb{x}\T\vb{z} + c)^p, c≥0c \ge 0pp, ccinteractions of up to pp variables
Gaussian (RBF)exp⁡(−γ∥x−z∥2)\exp(-\gamma\norm{\vb{x} - \vb{z}}^2)γ>0\gamma > 0closeness at scale 1/γ1/\sqrt{\gamma}
Laplacianexp⁡(−γ∥x−z∥1)\exp(-\gamma\norm{\vb{x} - \vb{z}}_1)γ>0\gamma > 0closeness, with less smooth functions
Intersection∑kmin⁡(xk,zk)\sum_k\min(x_k, z_k), x,z≥0\vb{x}, \vb{z} \ge \vb{0}histogram overlap
Spectrum∑ucu(s)cu(t)\sum_u c_u(s)c_u(t)length qqfragments shared by two strings
Sets∣A∩B∣\abs{A \cap B}common elements

Intersection is valid because min⁡(s,t)=∫0∞1[u≤s] 1[u≤t] ⁣du\min(s, t) = \int_0^\infty \ind[u \le s]\,\ind[u \le t]\dd u for s,t≥0s, t \ge 0: an inner product in L2L^2 of indicator functions, summed coordinate by coordinate (rule 1).

What is not a kernel

Validity matters for a concrete reason. The SVM dual minimizes 12α⊤Qα−1⊤α\tfrac12\vb{\alpha}\T\mat{Q}\vb{\alpha} - \vb{1}\T\vb{\alpha} with Q=diag⁡(y) K diag⁡(y)\mat{Q} = \diag(\vb{y})\,\mat{K}\,\diag(\vb{y}), positive semidefinite if and only if K\mat{K} is. If K\mat{K} has a negative eigenvalue, the objective is no longer convex: local optima may not be global, and in SMO pair curvature η=Kii+Kjj−2Kij\eta = K_{ii} + K_{jj} - 2K_{ij}, which with a valid kernel is ∥ϕ(xi)−ϕ(xj)∥2≥0\norm{\phi(\vb{x}_i) - \phi(\vb{x}_j)}^2 \ge 0, can be negative. “Distances” k(x,x)−2k(x,z)+k(z,z)k(\vb{x}, \vb{x}) - 2k(\vb{x}, \vb{z}) + k(\vb{z}, \vb{z}) can also be negative, and feature-space geometry disappears.

InteractiveIs it a valid kernel?
Gram matrix Kij=k(xi,xj)K_{ij} = k(\vb{x}_i, \vb{x}_j), 20 × 20
  • Kij<0K_{ij} < 0 (minimum −0.15)
  • Kij>0K_{ij} > 0 (maximum 0.98)
Spectrum of K\mat{K}, largest to smallest: negative eigenvalues in red
10¹10⁻²−10⁻²10⁻⁵−10⁻⁵0eigenvalue index
Signed log scale: ∣λ∣|\lambda| below 1e−7 are drawn as 0.
Parameters
1.00
1.00
20
Spectrum scale
λmax⁡\lambda_{\max}14.319
λmin⁡\lambda_{\min}−0.802
Negative eigenvalues8 of 20
Trace =∑iλi= \sum_i \lambda_i17.732
Not a kernel: 8 negative eigenvalues. With c\vb{c} the eigenvector of λmin⁡\lambda_{\min}, ∑ijcicjk(xi,xj)=−0.802<0\sum_{ij} c_i c_j k(\vb{x}_i, \vb{x}_j) = −0.802 < 0, and if k=ϕ⊤ϕk = \phi\T\phi this would be ∥∑iciϕ(xi)∥2≥0\norm{\sum_i c_i \phi(\vb{x}_i)}^2 \ge 0.
Gram matrix of the chosen function on nn uniform points in [−1,1]2[-1, 1]^2 and its spectrum, negative eigenvalues in red. Start with sigmoid tanh⁡(a x⊤z+c)\tanh(a\,\vb{x}\T\vb{z} + c), the ‘neural-network activation’ scikit-learn offers as a kernel: find aa and cc with no negative eigenvalues on any point set. Switch to polynomial and lower cc below 0. Try negative distance −∥x−z∥-\norm{\vb{x} - \vb{z}} (watch trace), then exp⁡(−γ∥x−z∥)\exp(-\gamma\norm{\vb{x} - \vb{z}}). Finally compose: what do ‘kk + RBF’, ‘k⋅k\cdotRBF’ and ‘normalizada’ (normalized) do to an invalid function?

What you should have found:

  • Sigmoid is not generally positive semidefinite. With a=c=1a = c = 1 and the initial 20 points, 8 of 20 eigenvalues are negative and the smallest is −0.80-0.80; parameters working on every point set are hard to find. Closure rules do not justify it: with c=0c = 0, tanh⁡\tanh has a Taylor series with alternating signs (t−t3/3+2t5/15−⋯t - t^3/3 + 2t^5/15 - \cdots), and with c>0c > 0 the coefficient of t2t^2 in tanh⁡(c+at)\tanh(c + at), −a2tanh⁡(c)/cosh⁡2(c)-a^2\tanh(c)/\cosh^2(c), is already negative. That alone does not rule it out (rules are sufficient, not necessary); the numerical counterexample does. Lin and Lin (2003) study parameter regions where it is at least conditionally positive definite, concluding it is generally no better than RBF. Sometimes working in practice does not make it a kernel.
  • Polynomial with c<0c < 0 becomes invalid. (x⊤z−1)2=(x⊤z)2−2x⊤z+1(\vb{x}\T\vb{z} - 1)^2 = (\vb{x}\T\vb{z})^2 - 2\vb{x}\T\vb{z} + 1 subtracts a kernel. With two points of R\R, x=1x = 1 and x=0x = 0, the Gram matrix is [0111]\begin{bmatrix} 0 & 1 \\ 1 & 1 \end{bmatrix}, determinant −1-1.
  • −∥x−z∥-\norm{\vb{x} - \vb{z}} is never valid. Its Gram diagonal is zero, so trace (sum of eigenvalues) is 0; if the matrix is nonzero, an eigenvalue is negative. The same holds for ∥x−z∥2\norm{\vb{x} - \vb{z}}^2. By contrast exp⁡(−γ∥x−z∥)\exp(-\gamma\norm{\vb{x} - \vb{z}}) is a kernel, though not by rule 7 (requiring the exponent be a kernel). Schoenberg’s exact criterion (1938) uses conditionally negative definite functions, a class containing ∥x−z∥β\norm{\vb{x} - \vb{z}}^\beta for 0<β≤20 < \beta \le 2.
  • Composing with a valid kernel may or may not repair it. Adding RBF to sigmoid adds a positive-definite matrix and shifts the spectrum upward, but not always enough; multiplying by RBF or normalizing does not turn an invalid function valid (rule 3 requires both factors be kernels).

The RBF kernel

Three properties make it special: it depends only on distance (translation and rotation invariant), equals 1 on the diagonal (all ϕ(x)\phi(\vb{x}) have norm 1 and lie on a sphere), and decays to 0 with distance, so distant points have almost orthogonal ϕ\phi.

Infinite dimension

In one dimension, the earlier factorization and exponential series give an explicit ϕ\phi:

e−γ(x−z)2=e−γx2e−γz2∑j=0∞(2γ)jxjzjj!=∑j=0∞ϕj(x)ϕj(z),ϕj(x)=e−γx2(2γ)jj! xj.e^{-\gamma(x - z)^2} = e^{-\gamma x^2}e^{-\gamma z^2}\sum_{j=0}^\infty\frac{(2\gamma)^j x^jz^j}{j!} = \sum_{j=0}^\infty\phi_j(x)\phi_j(z), \qquad \phi_j(x) = e^{-\gamma x^2}\sqrt{\frac{(2\gamma)^j}{j!}}\,x^j.

There is a coordinate for each degree: feature space is infinite-dimensional, containing polynomials of all degrees with weights decreasing as (2γ)j/j!(2\gamma)^j/j!. No finite ϕ\phi can reproduce it, as the next result states precisely.

Proof

The characteristic function of ω∼N(0,2γId)\boldsymbol{\omega} \sim \Normal(\vb{0}, 2\gamma\mat{I}_d) is E[eiω⊤v]=e−γ∥v∥2\E\big[e^{i\boldsymbol{\omega}\T\vb{v}}\big] = e^{-\gamma\norm{\vb{v}}^2}. With v=xj−xl\vb{v} = \vb{x}_j - \vb{x}_l,

c⊤Kc=∑j,lcjcl E[eiω⊤xj eiω⊤xl‾]=E[∣g(ω)∣2]≥0,g(ω)=∑jcjeiω⊤xj.\vb{c}\T\mat{K}\vb{c} = \sum_{j,l}c_jc_l\,\E\big[e^{i\boldsymbol{\omega}\T\vb{x}_j}\,\overline{e^{i\boldsymbol{\omega}\T\vb{x}_l}}\big] = \E\Big[\big|g(\boldsymbol{\omega})\big|^2\Big] \ge 0, \qquad g(\boldsymbol{\omega}) = \sum_j c_je^{i\boldsymbol{\omega}\T\vb{x}_j}.

If it were 00, since Gaussian density is positive throughout Rd\R^d and gg is continuous, g≡0g \equiv 0. Choose a direction u\vb{u} with distinct projections tj=u⊤xjt_j = \vb{u}\T\vb{x}_j (each pair j≠lj \neq l excludes only hyperplane u⊤(xj−xl)=0\vb{u}\T(\vb{x}_j - \vb{x}_l) = 0). Then h(s)=g(su)=∑jcjeistj≡0h(s) = g(s\vb{u}) = \sum_j c_je^{ist_j} \equiv 0, and its derivatives at s=0s = 0 yield ∑jcj(itj)r=0\sum_jc_j(it_j)^r = 0 for r=0,…,n−1r = 0, \dots, n-1: a Vandermonde system with distinct nodes whose only solution is c=0\vb{c} = \vb{0}. The last assertion follows because ϕ(xi)⊤ϕ(xj)\phi(\vb{x}_i)\T\phi(\vb{x}_j) with ϕ(xi)∈RD\phi(\vb{x}_i) \in \R^D has rank ≤D\le D.

∎

This proof previews two m13 ideas. Writing the kernel as an expectation over frequencies is Rahimi and Recht’s random-features model: sampling ω\boldsymbol{\omega} gives an approximate finite ϕ\phi. And invertibility of K\mat{K} has an immediate practical consequence: for any labels a combination f(x)=∑iβik(xi,x)f(\vb{x}) = \sum_i\beta_ik(\vb{x}_i, \vb{x}) interpolates them (solve Kβ=y\mat{K}\vb{\beta} = \vb{y}). An RBF-kernel model can memorize any training set; regularization, i.e. CC, prevents it.

γ as length scale and the two limits

γ\gamma sets the distance at which points stop resembling one another: k=e−1k = e^{-1} when ∥x−z∥=1/γ\norm{\vb{x} - \vb{z}} = 1/\sqrt{\gamma}. Its two extremes explain most tuning behavior.

  • γ→∞\gamma \to \infty. For distinct points K→I\mat{K} \to \mat{I}: each resembles only itself. An SVM with K=I\mat{K} = \mat{I} turns the whole training set into support vectors and decision function f(x)=∑iαiyik(xi,x)+bf(\vb{x}) = \sum_i\alpha_iy_ik(\vb{x}_i, \vb{x}) + b equals bb once x\vb{x} moves slightly away from data: an island of each training point’s class remains, and the rest of the plane belongs to the class favored by bb (with K=I\mat{K} = \mat{I} and large CC, the dual gives αi=1−yib\alpha_i = 1 - y_ib with b=(n+−n−)/nb = (n_+ - n_-)/n: the majority class). Pure memorization.
  • γ→0\gamma \to 0. Every point resembles every other: K→11⊤\mat{K} \to \vb{1}\vb{1}\T, a rank-1 matrix. But the model does not degenerate to a constant: to first order k≈1−γ∥x−z∥2k \approx 1 - \gamma\norm{\vb{x} - \vb{z}}^2, and the hyperparameter section shows the resulting SVM is linear with effective CC 2γC2\gamma C.

Between them is a band of useful values, whose location depends on data scale. Thus γ\gamma is meaningless without standardizing variables: if one is measured in meters and another in millimeters, the latter dominates ∥x−z∥2\norm{\vb{x} - \vb{z}}^2 and γ\gamma loses a common scale (you will check on real data below).

Kernel SVM

You have the pieces. The soft-margin SVM dual contains data only through xi⊤xj\vb{x}_i\T\vb{x}_j, and prediction through w⊤x=∑iαiyixi⊤x\vb{w}\T\vb{x} = \sum_i\alpha_iy_i\vb{x}_i\T\vb{x}. Replacing these products by kk applies the trick.

This is linear SVM in H\mathcal{H}, with w=∑iαiyiϕ(xi)\vb{w} = \sum_i\alpha_iy_i\phi(\vb{x}_i) never formed. With a valid kernel the dual is a concave quadratic program and everything from the previous lesson holds: complementary slackness, free and bounded support vectors, w\vb{w} depending only on supports. The only change is w\vb{w} can no longer be stored: support vectors and their αiyi\alpha_iy_i must be stored.

Interactiveγ and C in an RBF SVM
Boundary f(x)=0f(\vb{x}) = 0 and margins f(x)=±1f(\vb{x}) = \pm 1 of the RBF-kernel SVM, γ=31.6\gamma = 31.6, C=100C = 100
  • class +1
  • class −1
  • f=0f = 0
  • f=±1f = \pm 1
  • support vector: solid ring if free, dashed at bound CC
Accuracy on 400 validation points for each (γ,C)(\gamma, C); the circle marks the current position
7981818591917362617981818591917362617981828592917362617982838893917862618283869292878580668385889488848480668585908983828480668586928680818480668588928276818480668591868075818480668692847875818480660.010.11101000.010.11101001000γC
31.6
100
On click
Data
Support vectors: free and at bound CC58 and 0 (of 60)
Training accuracy100.0 %
Validation accuracy79.8 %
Best cell (γ,C)(\gamma, C)(0.32, 3.16)
Its validation accuracy93.8 %
Memorization: large γ\gamma makes each point an island. Training 100 %, validation 80 %, 58 of 60 points are support vectors.
Data: two interleaving moons with Gaussian noise 0.25 (60 training points) or two rings; validation has 400 new points from the same model. Initial state γ=31.6\gamma = 31.6 and C=100C = 100 gets all training correct: notice islands and validation accuracy. Slowly lower γ\gamma and watch islands merge. Then click through the grid and find good cells: round patch or band? Add wrong-class points in the middle of the other class with large γ\gamma and small γ\gamma. Solid rings mark free support vectors (0<αi<C0 < \alpha_i < C), dashed rings those at bound αi=C\alpha_i = C.

With γ=31.6\gamma = 31.6 length scale is 1/γ≈0.181/\sqrt{\gamma} \approx 0.18, much smaller than typical point separation: the model forms an island around each, 58 of 60 points are support vectors, training is perfect and validation drops near 80 %, versus 94 % for the best grid cell. Lowering γ\gamma toward 0.30.3 to 33, depending on CC, merges islands into two regions following the moons. Lowering γ\gamma further to 0.010.01 makes the boundary nearly straight and the model underfits. The grid summarizes all three; the hyperparameter section explains the diagonal band of good cells.

Kernel SMO and cache

The SMO algorithm changes nothing when kernelized: the maximally violating pair is chosen using st=yt−f0(xt)s_t = y_t - f_0(\vb{x}_t), and pair curvature is

η=Kii+Kjj−2Kij=∥ϕ(xi)−ϕ(xj)∥2.\eta = K_{ii} + K_{jj} - 2K_{ij} = \norm{\phi(\vb{x}_i) - \phi(\vb{x}_j)}^2.

Cost changes. Each step updates sts_t of nn points with columns ii and jj of K\mat{K}, and with a nonlinear kernel there is no explicit w\vb{w} summarizing data: each uncached column costs nn kernel evaluations, O(nd)\bigO(nd). The full matrix needs 8n28n^2 float64 bytes: 80 GB for n=105n = 10^5. LIBSVM (and its SVC wrapper) therefore computes columns as SMO requests them and stores recent ones in an LRU cache of size cache_size (200 MB by default in scikit-learn). This works because SMO, once support vectors are located, revisits the same indices. LIBSVM also uses shrinking: temporarily exclude αi\alpha_i that have stayed at a bound for many iterations.

The next cell takes previous-lesson SMO and replaces K\mat{K} with a column cache, counts computed columns and compares with SVC, both with kernel="rbf" and kernel="precomputed", passing the latter a precomputed Gram matrix.

[ ]Kernel SMO with column cacheBrowser
import time
import numpy as np
from collections import OrderedDict
from sklearn.svm import SVC
from sklearn.datasets import make_moons

class CacheColumnas:
    """Columnas de la matriz de Gram calculadas bajo demanda, con política LRU (como la caché de LIBSVM)."""
    def __init__(self, X, kernel, max_cols):
        self.X, self.kernel, self.max_cols = X, kernel, max_cols
        self.cols = OrderedDict()
        self.aciertos = self.fallos = 0
    def __call__(self, i):
        if i in self.cols:
            self.cols.move_to_end(i)
            self.aciertos += 1
        else:
            self.fallos += 1
            self.cols[i] = self.kernel(self.X, self.X[i:i + 1])[:, 0]
            if len(self.cols) > self.max_cols:
                self.cols.popitem(last=False)          # expulsa la usada hace más tiempo
        return self.cols[i]

def smo_kernel(X, y, kernel, C, tol=1e-3, max_cols=100, max_iter=100_000):
    """Dual del SVM: min ½ αᵀQα − 1ᵀα, 0 ≤ α ≤ C, yᵀα = 0, con Q_ij = y_i y_j k(x_i, x_j).
    Par de máxima violación y paso analítico, como en la lección anterior."""
    n = len(y)
    col = CacheColumnas(X, kernel, max_cols)
    diag = np.array([kernel(X[i:i + 1], X[i:i + 1])[0, 0] for i in range(n)])
    alpha, G = np.zeros(n), -np.ones(n)                # G = Qα − 1
    for it in range(max_iter):
        s = -y * G                                     # s_t = y_t − f₀(x_t)
        up = ((y > 0) & (alpha < C)) | ((y < 0) & (alpha > 0))
        low = ((y > 0) & (alpha > 0)) | ((y < 0) & (alpha < C))
        i = np.flatnonzero(up)[np.argmax(s[up])]
        j = np.flatnonzero(low)[np.argmin(s[low])]
        if s[i] - s[j] < tol:
            break
        Ki, Kj = col(i), col(j)
        eta = max(diag[i] + diag[j] - 2 * Ki[j], 1e-12)  # ‖φ(x_i) − φ(x_j)‖²
        t = min((s[i] - s[j]) / eta,                     # paso libre, recortado a la caja
                C - alpha[i] if y[i] > 0 else alpha[i],
                alpha[j] if y[j] > 0 else C - alpha[j])
        alpha[i] += y[i] * t
        alpha[j] -= y[j] * t
        G += y * (Ki - Kj) * t                           # columnas i y j de Q
    libre = (alpha > 1e-8) & (alpha < C - 1e-8)
    b = s[libre].mean() if libre.any() else (s[up].max() + s[low].min()) / 2
    return alpha, b, it, col

X, y01 = make_moons(300, noise=0.25, random_state=0)
y = 2.0 * y01 - 1
gamma, C = 1.0, 1.0
rbf = lambda A, B: k_rbf(A, B, gamma)
t = time.perf_counter(); alpha, b, its, cache = smo_kernel(X, y, rbf, C, max_cols=60); t_smo = time.perf_counter() - t
Xg = np.random.default_rng(2).uniform([-1.5, -1], [2.5, 1.5], (500, 2))
f_mio = rbf(Xg, X) @ (alpha * y) + b

t = time.perf_counter(); svc = SVC(C=C, gamma=gamma).fit(X, y); t_svc = time.perf_counter() - t
svp = SVC(C=C, kernel="precomputed").fit(rbf(X, X), y)          # la matriz de Gram, ya calculada
f_svc = svc.decision_function(Xg)
f_pre = svp.decision_function(rbf(Xg, X))                       # al predecir: k(x_nuevo, x_entrenamiento)
print(f"SMO desde cero: {its} iteraciones, {(alpha > 1e-8).sum()} vectores soporte "
      f"({((alpha > 1e-8) & (alpha < C - 1e-8)).sum()} libres), b = {b:.4f}")
print(f"SVC (rbf):         {svc.n_support_.sum()} vectores soporte, b = {svc.intercept_[0]:.4f}")
print(f"SVC (precomputed): {svp.n_support_.sum()} vectores soporte, b = {svp.intercept_[0]:.4f}")
print("mismos vectores soporte:", set(np.flatnonzero(alpha > 1e-8)) == set(svc.support_))
print(f"max |f_mío − f_SVC| en 500 puntos nuevos: {np.abs(f_mio - f_svc).max():.1e};"
      f"  rbf frente a precomputed: {np.abs(f_svc - f_pre).max():.1e}")
print(f"caché de 60 columnas: {cache.fallos} columnas calculadas y {cache.aciertos} aciertos; "
      f"{cache.fallos * len(y)} evaluaciones del kernel frente a n² = {len(y) ** 2}")
print(f"tiempo: SMO en Python {t_smo * 1e3:.0f} ms; SVC {t_svc * 1e3:.0f} ms")

The roughly 25-line SMO finds the same 73 support vectors as SVC (9 free), and decision functions agree to 10−310^{-3}, on the order of the stopping tolerance. With precomputed the result is identical up to rounding: this allows any kernel you compute, such as the string kernel at the end. A 60-column cache computes 83 columns total, under one third of the full matrix’s n2=90 000n^2 = 90\,000 evaluations, because SMO usually revisits indices.

Kernel SVM cost

  • Memory. Full Gram matrix uses 8n28n^2 bytes. With bounded cache memory is O(n)\bigO(n) plus cache, but each cache miss costs O(nd)\bigO(nd).
  • Training. Each SMO iteration costs O(n)\bigO(n) plus cache misses, and iteration count depends on the problem and CC and grows with nn: total is usually between O(n2)\bigO(n^2) and O(n3)\bigO(n^3), depending on class separability, CC and cache capacity. You will measure this in the Nyström section.
  • Prediction. O(∣S∣ d)\bigO(\abs{\mathcal{S}}\,d) per point: evaluate the kernel against each support vector. And ∣S∣\abs{\mathcal{S}} grows with nn. Steinwart (2003) showed that when classes overlap, support-vector fraction does not tend to zero: asymptotically it remains above Bayes risk. If Bayes risk is 10 %, a kernel SVM trained on one million points ultimately predicts using on the order of one hundred thousand support vectors or more.

These three figures motivate the Nyström approximation at the end of the lesson.

Support vector regression

The margin idea transfers to regression by replacing hinge loss with ε\varepsilon-insensitive loss, which does not penalize small residuals:

∣r∣ε=max⁡(0,∣r∣−ε),\abs{r}_\varepsilon = \max(0, \abs{r} - \varepsilon),

a variant of the first lesson’s regression losses: absolute loss with a dead zone of width 2ε2\varepsilon around zero.

Geometrically SVR seeks the flattest function (smallest ∥w∥\norm{\vb{w}}) whose tube f±εf \pm \varepsilon contains data, paying CC per unit a point protrudes. The dual follows as in SVM, with two multipliers per point, one per tube side.

L=12∥w∥2+C∑i(ξi+ξi∗)−∑i(μiξi+μi∗ξi∗)−∑iαi(ε+ξi−yi+fi)−∑iαi∗(ε+ξi∗+yi−fi)\begin{aligned} \mathcal{L} = {} & \tfrac12\norm{\vb{w}}^2 + C\textstyle\sum_i(\xi_i + \xi_i^*) \\ & - \textstyle\sum_i(\mu_i\xi_i + \mu_i^*\xi_i^*) \\ & - \textstyle\sum_i\alpha_i(\varepsilon + \xi_i - y_i + f_i) \\ & - \textstyle\sum_i\alpha_i^*(\varepsilon + \xi_i^* + y_i - f_i) \end{aligned}
Lagrangian with αi,αi∗,μi,μi∗≥0\alpha_i, \alpha_i^*, \mu_i, \mu_i^* \ge 0 and fi=w⊤ϕ(xi)+bf_i = \vb{w}\T\phi(\vb{x}_i) + b. Each constraint is written as “something ≥0\ge 0” and subtracted.
1/6

Complementary slackness explains sparsity. αi>0\alpha_i > 0 requires the first constraint active, yi−f(xi)=ε+ξi≥εy_i - f(\vb{x}_i) = \varepsilon + \xi_i \ge \varepsilon: the point lies at or above the tube’s upper edge. Likewise αi∗\alpha_i^* and the lower edge. Hence:

  • inside the tube, ∣yi−f(xi)∣<ε\abs{y_i - f(\vb{x}_i)} < \varepsilon: αi=αi∗=0\alpha_i = \alpha_i^* = 0 and the point does not enter ff;
  • on the boundary, ∣yi−f(xi)∣=ε\abs{y_i - f(\vb{x}_i)} = \varepsilon: 0≤∣βi∣≤C0 \le \abs{\beta_i} \le C;
  • outside, ∣yi−f(xi)∣>ε\abs{y_i - f(\vb{x}_i)} > \varepsilon: ξi>0\xi_i > 0 forces μi=0\mu_i = 0 and ∣βi∣=C\abs{\beta_i} = C.

Also αiαi∗=0\alpha_i\alpha_i^* = 0 if ε>0\varepsilon > 0: both constraints active simultaneously would require 0=2ε+ξi+ξi∗>00 = 2\varepsilon + \xi_i + \xi_i^* > 0. The solution depends only on points on or outside the tube, and ε\varepsilon controls how many.

InteractiveThe SVR tube
SVR with RBF kernel: f(x)=∑iβik(xi,x)+bf(x) = \sum_i \beta_i k(x_i, x) + b and tube f±εf \pm \varepsilon
−2−1012−3−2−10123
  • f(x)f(x)
  • tube f±εf \pm \varepsilon
  • true function
  • inside: βi=0\beta_i = 0
  • at edge: 0<∣βi∣<C0 < |\beta_i| < C
  • outside: ∣βi∣=C|\beta_i| = C
Number of support vectors versus ε\varepsilon, with current CC and γ\gamma
0.20
10
0.50
Support vectors (edge + outside)6 + 3 = 9 of 41
Inside tube, βi=0\beta_i = 032
∑iβi\sum_i \beta_i (must be 0)0.000000
Root mean squared error against sin⁡(1.5x)\sin(1.5x)0.122
Only the 9 points on or outside the tube have βi≠0\beta_i \neq 0; the 32 inside could be removed without changing ff.
Data from explicit model y=sin⁡(1.5x)+N(0,0.22)y = \sin(1.5x) + \Normal(0, 0.2^2) with xx uniform on [−3,3][-3, 3] (40 points) plus an outlier at x=0.6x = 0.6. Each point is colored by dual coefficient: hollow inside the tube (βi=0\beta_i = 0), blue on the edge, red with a ring outside (∣βi∣=C\abs{\beta_i} = C). Widen the tube and watch the curve below: how does support-vector count fall? Take ε\varepsilon to 0. Then lower CC: how far can the outlier pull the curve? Check ∑iβi\sum_i\beta_i stays 0.

Initially (ε=0.2\varepsilon = 0.2, C=10C = 10, γ=0.5\gamma = 0.5), 32 of 41 points are inside the tube and do not participate: the whole curve is supported by 9 support vectors, 6 on the edge and 3 outside. The outlier is outside, with ∣β∣=C\abs{\beta} = C: its pull is bounded, so SVR, like its underlying absolute loss, is robust. Lowering CC reduces that pull further, at the cost of many normal points also outside (with C=0.1C = 0.1, 28 of 41). With ε=0\varepsilon = 0 no point is inside and the solution loses sparsity.

The next cell solves the SVR dual using scipy.optimize.minimize (SLSQP, supporting bounds and an equality constraint), with 2n2n variables (α,α∗)(\vb{\alpha}, \vb{\alpha}^*) and the analytic gradient, comparing to SVR.

[ ]SVR dual with scipy.optimizeBrowser
import time
import numpy as np
from scipy.optimize import minimize
from sklearn.svm import SVR

def svr_dual(K, y, C, eps):
    """Minimiza ½ βᵀKβ + ε Σ(α + α*) − yᵀβ, con β = α − α*, 0 ≤ α, α* ≤ C y Σβ = 0."""
    n = len(y)
    def obj(z):
        beta = z[:n] - z[n:]
        Kb = K @ beta
        valor = 0.5 * beta @ Kb + eps * z.sum() - y @ beta
        grad = np.r_[Kb + eps - y, -Kb + eps + y]
        return valor, grad
    res = minimize(obj, np.zeros(2 * n), jac=True, method="SLSQP", bounds=[(0, C)] * (2 * n),
                   constraints=[{"type": "eq", "fun": lambda z: z[:n].sum() - z[n:].sum(),
                                 "jac": lambda z: np.r_[np.ones(n), -np.ones(n)]}],
                   options={"maxiter": 500, "ftol": 1e-12})
    a, a_ = res.x[:n], res.x[n:]
    beta, Kb, tc = a - a_, K @ (a - a_), 1e-6 * C
    # b con los puntos del borde: y − f = +ε si 0 < α < C;  y − f = −ε si 0 < α* < C
    bs = [y[i] - eps - Kb[i] for i in range(n) if tc < a[i] < C - tc]
    bs += [y[i] + eps - Kb[i] for i in range(n) if tc < a_[i] < C - tc]
    return beta, float(np.mean(bs)), res

rng = np.random.default_rng(3)
x = np.sort(rng.uniform(-3, 3, 50)); yv = np.sin(1.5 * x) + 0.2 * rng.normal(size=50)
Xr = x[:, None]
g_r, C_r, eps = 0.5, 10.0, 0.2
Kr = k_rbf(Xr, Xr, g_r)
t = time.perf_counter(); beta, b_r, res = svr_dual(Kr, yv, C_r, eps); t_sl = time.perf_counter() - t
svr = SVR(C=C_r, epsilon=eps, gamma=g_r, tol=1e-6).fit(Xr, yv)
xs = np.linspace(-3, 3, 200)[:, None]
f_mio = k_rbf(xs, Xr, g_r) @ beta + b_r
sv = np.abs(beta) > 1e-5 * C_r
print(f"SLSQP: {res.nit} iteraciones, {t_sl:.2f} s; Σβ = {beta.sum():.1e}")
print(f"vectores soporte: míos {sv.sum()}, SVR {len(svr.support_)}; los mismos: {set(np.flatnonzero(sv)) == set(svr.support_)}")
print(f"b: mío {b_r:.4f}, SVR {svr.intercept_[0]:.4f};  max |f_mío − f_SVR| = {np.abs(f_mio - svr.predict(xs)).max():.1e}")
r = yv - (Kr @ beta + b_r)
print(f"|residuo| de los que no son vectores soporte: máximo {np.abs(r[~sv]).max():.3f} (ε = {eps})")
print(f"|residuo| de los vectores soporte:            mínimo {np.abs(r[sv]).min():.3f}")
print("\n   ε    vectores soporte (de 50)")
for e in [0.0, 0.05, 0.1, 0.2, 0.3, 0.5]:
    print(f"{e:5.2f}   {len(SVR(C=C_r, epsilon=e, gamma=g_r).fit(Xr, yv).support_):3d}")

KKT conditions appear in the numbers: the 29 non-support points have residual at most 0.197<ε0.197 < \varepsilon and the 21 support vectors at least 0.200=ε0.200 = \varepsilon. The solution matches SVR to 10−610^{-6}. The final table shows sparsity: with ε=0\varepsilon = 0 all 50 points are support vectors, with ε=0.2\varepsilon = 0.2 (on the order of noise deviation) 21, and with ε=0.5\varepsilon = 0.5 only 6, at the cost of a curve no longer following data.

Choosing C, γ and ε together

An RBF SVM has two hyperparameters and SVR three, and they cannot be tuned separately. The earlier limit γ→0\gamma \to 0 explains why.

Proof

With k=1−γ∥xi−xj∥2+O(γ2)k = 1 - \gamma\norm{\vb{x}_i - \vb{x}_j}^2 + \bigO(\gamma^2) and ∥xi−xj∥2=∥xi∥2+∥xj∥2−2xi⊤xj\norm{\vb{x}_i - \vb{x}_j}^2 = \norm{\vb{x}_i}^2 + \norm{\vb{x}_j}^2 - 2\vb{x}_i\T\vb{x}_j, the dual quadratic term is

∑i,jαiαjyiyjkij=(∑iαiyi)2−2γ(∑iαiyi∥xi∥2)(∑jαjyj)+2γ∑i,jαiαjyiyjxi⊤xj+O(γ2).\sum_{i,j}\alpha_i\alpha_jy_iy_jk_{ij} = \Big(\sum_i\alpha_iy_i\Big)^2 - 2\gamma\Big(\sum_i\alpha_iy_i\norm{\vb{x}_i}^2\Big)\Big(\sum_j\alpha_jy_j\Big) + 2\gamma\sum_{i,j}\alpha_i\alpha_jy_iy_j\vb{x}_i\T\vb{x}_j + \bigO(\gamma^2).

The first two terms vanish by constraint ∑iαiyi=0\sum_i\alpha_iy_i = 0. With substitution α=β/(2γ)\vb{\alpha} = \vb{\beta}/(2\gamma), the dual becomes 12γ[∑iβi−12∑i,jβiβjyiyjxi⊤xj]\frac{1}{2\gamma}\big[\sum_i\beta_i - \frac12\sum_{i,j}\beta_i\beta_jy_iy_j\vb{x}_i\T\vb{x}_j\big] with 0≤βi≤2γC0 \le \beta_i \le 2\gamma C: the linear SVM dual with C~=2γC\tilde C = 2\gamma C, multiplied by a positive constant that does not change the maximizer. The decision transforms similarly: f(x)=∑iαiyi(1−γ∥xi∥2−γ∥x∥2+2γxi⊤x)+bf(\vb{x}) = \sum_i\alpha_iy_i\big(1 - \gamma\norm{\vb{x}_i}^2 - \gamma\norm{\vb{x}}^2 + 2\gamma\vb{x}_i\T\vb{x}\big) + b, where constant terms in ii vanish by the same constraint, leaving ∑iβiyixi⊤x\sum_i\beta_iy_i\vb{x}_i\T\vb{x} plus a constant.

∎

Keerthi and Lin (2003) rigorously study these limits (including very large CC and γ\gamma) and derive a practical consequence: after a full search over (C,γ)(C, \gamma) with Gaussian kernel, there is no need to separately try linear SVM, contained in one grid corner. The proposition says something more useful for search: in the small-γ\gamma region the model depends only on product γC\gamma C, so on (log⁡γ,log⁡C)(\log\gamma, \log C) axes equal-quality curves are lines of slope −1-1. Lower γ\gamma tenfold and raise CC tenfold to retain the model. Outside that region the exact relation changes but compensation persists: larger γ\gamma makes the function more flexible and calls for smaller CC to restrain it. Tuning γ\gamma with fixed CC and then CC with fixed γ\gamma traverses a cross and misses the diagonal. A joint logarithmic grid works: Hsu, Chang and Lin’s practical guide recommends first scaling variables (to [−1,1][-1, 1] or [0,1][0, 1]), starting with C=2−5,2−3,…,215C = 2^{-5}, 2^{-3}, \dots, 2^{15} and γ=2−15,2−13,…,23\gamma = 2^{-15}, 2^{-13}, \dots, 2^{3}, then refining around the best point.

First, why scale. The breast_cancer dataset has variables with standard deviations between 0.00260.0026 and 569569.

[ ]Scaling before the RBF kernelBrowser
import numpy as np
from sklearn.svm import SVC
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_breast_cancer

Xb, yb = load_breast_cancer(return_X_y=True)
dev = Xb.std(0)
print(f"desviaciones típicas de las variables: de {dev.min():.4f} a {dev.max():.1f}")
print(f"la variable más dispersa aporta el {100 * Xb[:, dev.argmax()].var() / Xb.var(0).sum():.1f} % de ‖x − z‖² en media")
sin = cross_val_score(SVC(), Xb, yb, cv=5).mean()
con = cross_val_score(make_pipeline(StandardScaler(), SVC()), Xb, yb, cv=5).mean()
print(f"SVC RBF con gamma='scale', validación cruzada de 5 pliegues: sin escalar {sin:.3f}, con StandardScaler {con:.3f}")

Unscaled, one of 30 variables contributes 71.7 % of expected squared distance between points: the kernel almost only sees that variable. Standardizing (inside the pipeline so data leakage does not contaminate validation) raises accuracy from 0.912 to 0.974 with no other change. scikit-learn’s default gamma="scale", γ=1/(d Var⁡^(X))\gamma = 1/(d\,\widehat{\Var}(\mat{X})) using variance of all entries of X\mat{X}, sets a reasonable global scale but cannot correct differing variable scales.

Now the grid. With comparable variable scales, a grid search over (C,γ)(C, \gamma) on noisy two moons:

[ ]The diagonal of good valuesBrowser
import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import make_moons

Xm, ym = make_moons(300, noise=0.3, random_state=1)
Cs = 10.0 ** np.arange(-2, 4.1, 0.75)
gammas = 10.0 ** np.arange(-2.5, 2.1, 0.5)
gs = GridSearchCV(SVC(), {"C": Cs, "gamma": gammas}, cv=3).fit(Xm, ym)
S = gs.cv_results_["mean_test_score"].reshape(len(Cs), len(gammas))
print("mejor:", {k: float(f"{v:.4g}") for k, v in gs.best_params_.items()}, f"exactitud {gs.best_score_:.3f}")
print("gamma='scale' daría γ =", round(1 / (Xm.shape[1] * Xm.var()), 3))
print("              γ:" + "".join(f"{g:7.3g}" for g in gammas))
for i in range(len(Cs) - 1, -1, -1):
    print(f"C = {Cs[i]:9.3g}  " + "".join(f"{s:7.2f}" for s in S[i]))
plt.figure(figsize=(6, 4))
plt.imshow(S, origin="lower", cmap="viridis", aspect="auto",
           extent=[np.log10(gammas[0]) - 0.25, np.log10(gammas[-1]) + 0.25,
                   np.log10(Cs[0]) - 0.375, np.log10(Cs[-1]) + 0.375])
plt.colorbar(label="exactitud de validación cruzada")
plt.xlabel("log10 γ"); plt.ylabel("log10 C"); plt.show()

# la proposición, comprobada: RBF con γ pequeño frente a SVM lineal con C̃ = 2γC
Xg = np.random.default_rng(0).uniform([-2, -1.5], [3, 2], (2000, 2))
for g, C in [(1e-3, 1e3), (1e-2, 1e2), (1e-1, 1e1)]:
    f_rbf = SVC(gamma=g, C=C, tol=1e-6).fit(Xm, ym).decision_function(Xg)
    for Ct in [2 * g * C, 0.02]:
        f_lin = SVC(kernel="linear", C=Ct, tol=1e-6).fit(Xm, ym).decision_function(Xg)
        print(f"RBF γ = {g:g}, C = {C:g}  frente a  lineal C̃ = {Ct:g}: "
              f"misma clase en el {100 * np.mean(np.sign(f_rbf) == np.sign(f_lin)):.1f} % de 2000 puntos, "
              f"max |f_RBF − f_lin| = {np.abs(f_rbf - f_lin).max():.3f}")

The table shows the interactive’s three regions. Cells with accuracy 0.91 to 0.93 form a descending band left to right: (γ,C)=(0.1,104)(\gamma, C) = (0.1, 10^4), (0.316,316)(0.316, 316), (1,10)(1, 10), (3.16,1.78)(3.16, 1.78), (10,0.316)(10, 0.316). At lower left, small γ\gamma and CC make the model nearly linear, achieving 0.78–0.85. At right, with γ=100\gamma = 100, no CC exceeds 0.84: CC cannot fix memorization. The best cell, C=104C = 10^4 and γ=0.1\gamma = 0.1, lies at the edge of the CC grid, requiring expansion in a real search; here the band already shows nearly as good cells with moderate CC.

Notice the band’s slope: between γ=0.1\gamma = 0.1 and γ=1\gamma = 1, whenever γ\gamma multiplies by 10\sqrt{10} the best CC divides by about 30; between 11 and 1010, about 6. The proposition’s slope −1-1 would divide by 10≈3.2\sqrt{10} \approx 3.2 and need not hold here: with γ≥0.1\gamma \ge 0.1 and data occupying roughly three units, γ∥x−z∥2\gamma\norm{\vb{x} - \vb{z}}^2 is no longer small and the model is truly nonlinear. The proposition describes the small-γ\gamma corner, where the final cell check is striking: with γ=0.001\gamma = 0.001 and C=1000C = 1000, RBF SVM and linear SVM with C~=2\tilde C = 2 assign the same class to 99.5 % of points in a broad region and their decision functions differ by at most 0.14; with wrong C~\tilde C (0.020.02), agreement falls to 88 %. With γ=0.1\gamma = 0.1 the approximation no longer holds (89.2 % agreement). Across the grid the diagonal shape remains: γ\gamma and CC compensate, so must be searched together.

SVR’s grid has a third dimension ε\varepsilon, measured in units of yy. Two practical rules: standardize yy too (or scale ε\varepsilon by its deviation), and search ε\varepsilon on the order of noise standard deviation, estimable from residuals of a first fit. With ε\varepsilon much greater than noise the tube swallows signal; much smaller and the solution loses sparsity without gaining accuracy. To avoid an entire cubic grid, commonly fix ε\varepsilon by that rule, search (C,γ)(C, \gamma) and refine ε\varepsilon last, or use logarithmic-scale random search.

Scaling to many data points: Nyström approximation

A kernel SVM needs Gram matrix n×nn \times n in some form, and with n=105n = 10^5 the full float64 matrix already occupies 80 GB. Williams and Seeger’s (2001) idea, used on USPS and abalone with m≪nm \ll n without significant accuracy loss, approximates K\mat{K} by a rank-m≪nm \ll n matrix built from only mm columns.

With these, any kernel method becomes the corresponding linear method on r≤mr \le m features: kernel SVM becomes linear SVM on ϕ~(x)\tilde\phi(\vb{x}). What exactly is approximated?

Proof

Pϕ(x)=∑jcjϕ(zj)P\phi(\vb{x}) = \sum_jc_j\phi(\vb{z}_j) with c\vb{c} solving normal equations Kmmc=km(x)\mat{K}_{mm}\vb{c} = \vb{k}_m(\vb{x}), where km(x)=(k(zj,x))j\vb{k}_m(\vb{x}) = \big(k(\vb{z}_j, \vb{x})\big)_j; one solution is c=Kmm+km(x)\vb{c} = \mat{K}_{mm}^{+}\vb{k}_m(\vb{x}) because km(x)\vb{k}_m(\vb{x}) lies in the image of Kmm\mat{K}_{mm}: if Kmmv=0\mat{K}_{mm}\vb{v} = \vb{0}, then ∥∑jvjϕ(zj)∥2=v⊤Kmmv=0\norm{\sum_jv_j\phi(\vb{z}_j)}^2 = \vb{v}\T\mat{K}_{mm}\vb{v} = 0 and v⊤km(x)=⟨∑jvjϕ(zj),ϕ(x)⟩=0\vb{v}\T\vb{k}_m(\vb{x}) = \inner{\sum_jv_j\phi(\vb{z}_j)}{\phi(\vb{x})} = 0, so km(x)\vb{k}_m(\vb{x}) is orthogonal to the null space of symmetric Kmm\mat{K}_{mm}. Projection is unique even if c\vb{c} is not. Since PP is self-adjoint and idempotent, ⟨Pϕ(x),Pϕ(x′)⟩=⟨Pϕ(x),ϕ(x′)⟩=∑jcjk(zj,x′)=km(x)⊤Kmm+km(x′)\inner{P\phi(\vb{x})}{P\phi(\vb{x}')} = \inner{P\phi(\vb{x})}{\phi(\vb{x}')} = \sum_jc_jk(\vb{z}_j, \vb{x}') = \vb{k}_m(\vb{x})\T\mat{K}_{mm}^{+}\vb{k}_m(\vb{x}'). (1) For x=zj\vb{x} = \vb{z}_j, ϕ(zj)\phi(\vb{z}_j) is already in the subspace and Pϕ(zj)=ϕ(zj)P\phi(\vb{z}_j) = \phi(\vb{z}_j). (2) ⟨ϕ(x),ϕ(x′)⟩−⟨Pϕ(x),Pϕ(x′)⟩=⟨(I−P)ϕ(x),(I−P)ϕ(x′)⟩\inner{\phi(\vb{x})}{\phi(\vb{x}')} - \inner{P\phi(\vb{x})}{P\phi(\vb{x}')} = \inner{(I - P)\phi(\vb{x})}{(I - P)\phi(\vb{x}')}, a kernel (for map (I−P)ϕ(I - P)\phi). Equivalently K−K~\mat{K} - \tilde{\mat{K}} is the Schur complement of Kmm\mat{K}_{mm} in the joint landmark-and-data Gram matrix.

∎

The theorem locates approximation failure: points whose image ϕ(x)\phi(\vb{x}) is far from the landmark space. With RBF this literally means far from all landmarks, because ∥ϕ(x)−Pϕ(x)∥2≤∥ϕ(x)−ϕ(zj)∥2=2−2e−γ∥x−zj∥2\norm{\phi(\vb{x}) - P\phi(\vb{x})}^2 \le \norm{\phi(\vb{x}) - \phi(\vb{z}_j)}^2 = 2 - 2e^{-\gamma\norm{\vb{x} - \vb{z}_j}^2} for each jj. Hence selection matters:

  • Uniform sampling of mm data points, the original proposal. It follows data density: sparsely populated regions receive few or no landmarks.
  • k-means centers. Zhang, Tsang and Kwok (2008) bound Nyström error by landmark quantization error, directly motivating k-means centroids. Centroids cover data space more evenly than a sample.
  • Adaptive choices select each point by residual from previous ones, such as randomly pivoted Cholesky.
InteractiveNyström: few landmarks, nearly the same kernel
Background: residual k(x,x)−K~(x,x)k(\vb{x}, \vb{x}) - \tilde K(\vb{x}, \vb{x}), from 0 (background color) to 1 (gray)
  • class +1
  • class −1
  • landmark (diamond)
  • exact SVM boundary
  • Nyström + linear SVM boundary
∣K−K~∣|\mat{K} - \tilde{\mat{K}}|, data ordered by class and x1x_1 (0 to 0.5 or more)
Relative trace error versus mm (log scale); uniform: mean of 3 draws
  • uniform
  • k-means
10
Selection method
Background
Relative trace error tr⁡(K−K~)/tr⁡K\tr(\mat{K} - \tilde{\mat{K}})/\tr \mat{K}41.0 %
Relative Frobenius error42.5 %
Test accuracy: exact and Nyström99.3 % and 98.3 %
Agreement with exact SVM98.6 %
Exact support vectors; rank of Kmm\mat{K}_{mm}29; 10
Uniform sampling: landmarks follow data density and leave sparsely populated tips uncovered (gray background). Agreement with exact: 98.6 %.
Two moons with density concentrated at one end (explicit model: angle t=πu2.2t = \pi u^{2.2} with uniform uu, noise 0.12; 400 training and 2000 test points), RBF kernel with γ=2\gamma = 2 and C=10C = 10. Dashed line is exact SVM boundary; solid line is linear SVM trained on Nyström features. Background is residual k(x,x)−K~(x,x)k(\vb{x}, \vb{x}) - \tilde K(\vb{x}, \vb{x}): gray where landmarks (diamonds) do not reach. Start with 10 uniform points: which data regions remain gray? Switch to k-means at the same mm. Click ‘Otro sorteo’ (another draw) several times. In the lower plot compare landmark counts needed for equal error.

With uniform sampling, most landmarks fall in dense regions and sparse moon tips remain gray: there K~(x,x)\tilde K(\vb{x}, \vb{x}) is far from 1, Nyström has little information and its boundary diverges from exact precisely there. With k-means diamonds cover the data region and residual drops there. In the plot k-means needs about half as many points for equal trace error: with 12 it reaches 0.20, which uniform sampling (mean of three draws) reaches only at 24; with 16 it reaches 0.12, which uniform reaches only at mm between 30 and 40. Notice the ∣K−K~∣\abs{\mat{K} - \tilde{\mat{K}}} map too: error concentrates in blocks, rows and columns of poorly covered points.

From scratch

Implementation is short: eigendecompose Kmm\mat{K}_{mm}, discard near-zero eigenvalues (repeated or very close landmarks make Kmm\mat{K}_{mm} numerically singular), and multiply. Error is measured by trace, which since K−K~\mat{K} - \tilde{\mat{K}} is positive semidefinite is also its nuclear norm and costs O(nr)\bigO(nr): tr⁡(K−K~)=∑i(k(xi,xi)−∥ϕ~(xi)∥2)\tr(\mat{K} - \tilde{\mat{K}}) = \sum_i\big(k(\vb{x}_i, \vb{x}_i) - \norm{\tilde\phi(\vb{x}_i)}^2\big).

[ ]Nyström from scratch: uniform versus k-meansBrowser
import time
import numpy as np
from sklearn.svm import SVC, LinearSVC
from sklearn.cluster import KMeans

def lunas_desiguales(n, ruido, rng, pot=2.2):
    """Dos lunas con el ángulo t = π u^pot: los puntos se concentran cerca de t = 0."""
    t = np.pi * rng.uniform(size=n) ** pot
    c = np.where(np.arange(n) % 2 == 0, 1, -1)
    x = np.where(c == 1, np.cos(t), 1 - np.cos(t))
    y = np.where(c == 1, np.sin(t), 0.5 - np.sin(t))
    return 1.6 * (np.c_[x - 0.5, y - 0.25] + ruido * rng.normal(size=(n, 2))), c

def nystrom_features(X, Z, kernel, rtol=1e-10):
    """F tal que F Fᵀ = K_nm K_mm⁺ K_mn: F = K_nm U Λ^{−1/2}, con los autovalores > rtol·λ_max."""
    lam, U = np.linalg.eigh(kernel(Z, Z))
    keep = lam > rtol * lam.max()
    T = U[:, keep] / np.sqrt(lam[keep])
    return kernel(X, Z) @ T, T

rng = np.random.default_rng(5)
X, y = lunas_desiguales(2000, 0.12, rng)
Xt, yt = lunas_desiguales(5000, 0.12, rng)
gamma, C = 2.0, 10.0
ker = lambda A, B: k_rbf(A, B, gamma)
t = time.perf_counter(); exacto = SVC(C=C, gamma=gamma).fit(X, y); t_ex = time.perf_counter() - t
p_ex = exacto.predict(Xt)
print(f"SVC exacto: {exacto.n_support_.sum()} vectores soporte, exactitud {np.mean(p_ex == yt):.4f}, {t_ex:.2f} s")
print("\n  m  elección   error de traza   exactitud   coincide con el exacto")
for m in [5, 10, 20, 50]:
    for nombre in ["uniforme", "k-means"]:
        if nombre == "uniforme":
            Z = X[np.random.default_rng(m).choice(len(X), m, replace=False)]
        else:
            Z = KMeans(m, n_init=1, random_state=0).fit(X).cluster_centers_
        F, T = nystrom_features(X, Z, ker)
        lin = LinearSVC(C=C, max_iter=5000).fit(F, y)
        err = 1 - (F ** 2).sum() / len(X)               # tr(K − K̃)/tr(K), con k(x, x) = 1
        p = lin.predict(ker(Xt, Z) @ T)
        print(f"{m:3d}  {nombre:9s} {err:12.4f} {np.mean(p == yt):13.4f} {np.mean(p == p_ex):14.4f}")

# Nyström frente a características aleatorias de Fourier, con el mismo número de features
S = X[:800]
K = ker(S, S)
print("\nerror relativo de Frobenius de la matriz de Gram (800 puntos)")
print("  D    Nyström k-means   Fourier aleatorias")
for D in [10, 20, 50, 100]:
    Z = KMeans(D, n_init=1, random_state=0).fit(X).cluster_centers_
    F, _ = nystrom_features(S, Z, ker)
    W = np.random.default_rng(D).normal(scale=np.sqrt(2 * gamma), size=(2, D))
    bb = np.random.default_rng(D + 1).uniform(0, 2 * np.pi, D)
    R = np.sqrt(2 / D) * np.cos(S @ W + bb)            # Rahimi y Recht: E[RRᵀ] = K
    fro = lambda A: np.linalg.norm(K - A) / np.linalg.norm(K)
    print(f"{D:3d}  {fro(F @ F.T):14.4f}  {fro(R @ R.T):17.4f}")

Numbers confirm the figure with five times more data. Exact SVC reaches 99.34 % with 53 support vectors. With m=10m = 10, k-means matches it already (trace error 0.27, agreement 99.9 %), while 10 uniform points achieve 97.2 % with trace error 0.46; uniform sampling needs about 20 to reach the same level. With m=50m = 50 both strategies reproduce the exact model, but k-means trace error is four times lower (0.010 versus 0.041).

The final table compares Nyström with a practical alternative. Rahimi and Recht’s (2007) random Fourier features turn the RBF theorem proof into an algorithm: sample DD frequencies ωk∼N(0,2γI)\boldsymbol{\omega}_k \sim \Normal(\vb{0}, 2\gamma\mat{I}) and phases bk∼Unif⁡[0,2π]b_k \sim \Unif[0, 2\pi], and use r(x)=2/D (cos⁡(ωk⊤x+bk))k\vb{r}(\vb{x}) = \sqrt{2/D}\,\big(\cos(\boldsymbol{\omega}_k\T\vb{x} + b_k)\big)_k, whose inner product is the kernel in expectation. They do not look at data and thus do not adapt; with the same feature count their Gram error here is much greater than Nyström’s: with D=50D = 50, 0.42 versus 0.008. Fourier error falls slowly at the Monte Carlo average rate 1/D1/\sqrt{D} (0.39 with D=100D = 100, with single-draw noise), while Nyström falls to 0.0008. This agrees with Yang et al. (2012), who compare both methods on many datasets: Nyström draws basis functions from data and when K\mat{K}’s spectrum has a large gap between dominant eigenvalues and the rest, its generalization-error bound is notably better. In exchange Fourier features require neither a data pass nor decomposition; their analysis (feature count for a given error) is m13’s random-feature approximation error.

Cost and gain

Feature construction costs O(nmd)\bigO(nmd) for Knm\mat{K}_{nm}, O(m3)\bigO(m^3) for decomposition and O(nmr)\bigO(nmr) for multiplication; memory is O(nm)\bigO(nm). Linear SVM over rr features costs about nrnr per epoch and prediction per point O(md+mr)\bigO(md + mr), independent of nn. The next cell measures growth with nn from 1000 to 20 000 on your machine (local because exact SVM on 20 000 points takes too long for the browser). It uses moons with noise 0.3, where classes overlap and support-vector count grows with nn, and compares exact SVC, your k-means Nyström, scikit-learn Nystroem (uniform landmarks) and RBFSampler (random Fourier), all with LinearSVC on top.

[ ]Exact SVC versus Nyström and Fourier, 1000 to 20 000 pointsLocal GPU
import time
import numpy as np
from sklearn.svm import SVC, LinearSVC
from sklearn.kernel_approximation import Nystroem, RBFSampler
from sklearn.cluster import KMeans
from sklearn.pipeline import make_pipeline

def lunas_desiguales(n, ruido, rng, pot=2.2):
    t = np.pi * rng.uniform(size=n) ** pot
    c = np.where(np.arange(n) % 2 == 0, 1, -1)
    x = np.where(c == 1, np.cos(t), 1 - np.cos(t))
    y = np.where(c == 1, np.sin(t), 0.5 - np.sin(t))
    return 1.6 * (np.c_[x - 0.5, y - 0.25] + ruido * rng.normal(size=(n, 2))), c

def rbf(A, B, gamma):
    d2 = (A ** 2).sum(1)[:, None] + (B ** 2).sum(1)[None, :] - 2 * A @ B.T
    return np.exp(-gamma * np.maximum(d2, 0.0))

def nystrom_kmeans(X, m, gamma, seed=0):
    Z = KMeans(m, n_init=1, random_state=seed).fit(X).cluster_centers_
    lam, U = np.linalg.eigh(rbf(Z, Z, gamma))
    keep = lam > 1e-10 * lam.max()
    T = U[:, keep] / np.sqrt(lam[keep])
    return lambda A: rbf(A, Z, gamma) @ T

gamma, C, m = 2.0, 10.0, 50
rng = np.random.default_rng(7)
Xt, yt = lunas_desiguales(20000, 0.3, rng)
print("     n | SVC exacto: tiempo, vectores soporte, exactitud | Nyström k-means m=50 | Nystroem m=50 | RBFSampler D=50 | RBFSampler D=500")
for n in [1000, 2000, 5000, 10000, 20000]:
    X, y = lunas_desiguales(n, 0.3, rng)
    fila = [f"{n:6d}"]
    t = time.perf_counter(); ex = SVC(C=C, gamma=gamma, cache_size=500).fit(X, y); te = time.perf_counter() - t
    fila.append(f"{te:6.2f} s {ex.n_support_.sum():6d} {np.mean(ex.predict(Xt) == yt):.4f}")
    t = time.perf_counter(); fmap = nystrom_kmeans(X, m, gamma); lin = LinearSVC(C=C).fit(fmap(X), y); tn = time.perf_counter() - t
    fila.append(f"{tn:5.2f} s {np.mean(lin.predict(fmap(Xt)) == yt):.4f}")
    for est in [Nystroem(gamma=gamma, n_components=m, random_state=0),
                RBFSampler(gamma=gamma, n_components=50, random_state=0),
                RBFSampler(gamma=gamma, n_components=500, random_state=0)]:
        t = time.perf_counter(); p = make_pipeline(est, LinearSVC(C=C)).fit(X, y); ta = time.perf_counter() - t
        fila.append(f"{ta:5.2f} s {np.mean(p.predict(Xt) == yt):.4f}")
    print(" | ".join(fila))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In our run (times depend on your machine; trends do not), exact SVC support-vector count grows proportionally to nn, from 407 with 1000 points to 6983 with 20 000, always 35–41 % of data, and training time grows much faster than nn: quadrupling data from 5000 to 20 000 multiplied time over tenfold. Nyström with 50 landmarks scales roughly linearly and, at 20 000 points, trains over ten times faster with the same accuracy (0.838 versus 0.839; class overlap sets the ceiling, not the model). Fourier features with D=50D = 50 also reach that ceiling in this two-dimensional problem; with D=500D = 500 they gain no accuracy and are slowest because LinearSVC handles ten times as many columns. As accuracy saturates, this table compares costs; the previous cell’s Gram error better measures Nyström–Fourier quality differences.

The scikit-learn version

ClassPurposeImportant details
SVC(kernel="rbf", C, gamma)kernel SVM (LIBSVM)gamma="scale" by default; cache_size in MB; one-versus-one multiclass
SVR(C, epsilon, gamma), NuSVRSVR ε\varepsilon and ν\nuscale yy or ε\varepsilon; support_, dual_coef_ =βi= \beta_i
SVC(kernel="precomputed")SVM with your Gram matrixfit(K_train, y), predict(K_test_train) with shape ntest×nn_{\text{test}}\times n
SVC(kernel=funcion)kernel as Python functionreceives two matrices and returns their Gram
Nystroem(kernel, gamma, n_components)Nyström features with uniform pointschain with LinearSVC, SGDClassifier or Ridge
RBFSampler(gamma, n_components)random Fourier for RBFno data fit

The final cell combines everything with a kernel on nonvector data: the spectrum kernel over DNA sequences, with a manually computed Gram matrix passed as precomputed. Negative sequences are random; positive ones also have fragment TATAAT (the Pribnow box of bacterial promoters) inserted at a random position.

[ ]With libraries: RBF pipeline, Nystroem and a precomputed string kernelBrowser
import numpy as np
from sklearn.svm import SVC
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.kernel_approximation import Nystroem
from sklearn.datasets import load_breast_cancer

# 1. El pipeline estándar: escalar dentro del pipeline, SVC RBF con C y gamma a la vez
Xb, yb = load_breast_cancer(return_X_y=True)
for C, g in [(1, "scale"), (10, 0.01), (100, 0.001)]:
    pipe = make_pipeline(StandardScaler(), SVC(C=C, gamma=g))
    print(f"SVC C = {C:3d}, gamma = {g!s:6s}: {cross_val_score(pipe, Xb, yb, cv=5).mean():.3f}")
pipe_ny = make_pipeline(StandardScaler(), Nystroem(gamma=1 / 30, n_components=100, random_state=0), SVC(kernel="linear", C=1))
print(f"Nystroem (100) + SVM lineal: {cross_val_score(pipe_ny, Xb, yb, cv=5).mean():.3f}")

# 2. Un kernel sobre cadenas: el kernel de espectro, k(s, t) = Σ_u c_u(s) c_u(t)
rng = np.random.default_rng(0)
ALF = np.array(list("ACGT"))
def secuencia(positiva, L=60):
    s = "".join(rng.choice(ALF, L))
    if positiva:
        p = rng.integers(0, L - 6)
        s = s[:p] + "TATAAT" + s[p + 6:]
    return s
seqs = [secuencia(i % 2 == 1) for i in range(400)]
lab = np.array([i % 2 for i in range(400)])

def espectro(seqs, q):
    """Matriz n × 4^q con el número de apariciones de cada fragmento de longitud q."""
    cod = {"A": 0, "C": 1, "G": 2, "T": 3}
    M = np.zeros((len(seqs), 4 ** q))
    for i, s in enumerate(seqs):
        v = np.array([cod[ch] for ch in s])
        idx = np.zeros(len(s) - q + 1, dtype=int)
        for j in range(q):
            idx = 4 * idx + v[j:len(s) - q + 1 + j]
        M[i] = np.bincount(idx, minlength=4 ** q)
    return M

tr, te = train_test_split(np.arange(400), test_size=0.5, random_state=0, stratify=lab)
for q in [2, 4, 6]:
    M = espectro(seqs, q)
    K = M @ M.T
    d = np.sqrt(np.diag(K))
    Kn = K / np.outer(d, d)                              # normalización: regla 8
    svm = SVC(kernel="precomputed", C=1).fit(Kn[np.ix_(tr, tr)], lab[tr])
    acc = (svm.predict(Kn[np.ix_(te, tr)]) == lab[te]).mean()
    print(f"kernel de espectro q = {q}: {4 ** q:5d} fragmentos posibles, exactitud de prueba {acc:.3f}, "
          f"{len(svm.support_)} vectores soporte de {len(tr)}")

In part one, well-scaled RBF SVC gives 0.970–0.979 with three diagonal combinations, and Nyström with 100 components plus linear SVM gives 0.975: at 569 points approximation is unnecessary but loses nothing. In part two, accuracy increases with fragment length: 0.740 with q=2q = 2, where the motif dilutes among 16 background fragments; 0.895 with q=4q = 4, and 0.985 with q=6q = 6, where the kernel compares exactly the discriminating fragment and SVM finds it without being told which. Notice cost: with q=6q = 6, 197 of 200 points are support vectors. Each sequence has only 55 of 4096 possible fragments, two sequences share very few, and the normalized Gram matrix resembles identity: the same phenomenon as large-γ\gamma RBF. With large qq, 4q4^q coordinates no longer fit in a dense matrix, but each length-LL sequence contains only L−q+1L - q + 1 fragments: serious implementations compute kk with sparse structures or suffix trees, never constructing the count vector.

Typical mistakes

Exercises

NumericPolynomial kernel dimension
What is the feature-space dimension of polynomial kernel k(x,z)=(x⊤z+1)3k(\vb{x}, \vb{z}) = (\vb{x}\T\vb{z} + 1)^3 with x∈R10\vb{x} \in \R^{10}?
ProofDegree-2 polynomial is a kernel
Prove: For c≥0c \ge 0, k(x,z)=(x⊤z+c)2k(\vb{x}, \vb{z}) = (\vb{x}\T\vb{z} + c)^2 with x,z∈R2\vb{x}, \vb{z} \in \R^2 is a kernel.
0
Find ϕ:R2→RD\phi : \R^2 \to \R^D with k(x,z)=ϕ(x)⊤ϕ(z)k(\vb{x}, \vb{z}) = \phi(\vb{x})\T\phi(\vb{z}).

Step 1 of 4. How do you start?

ProofDistances and centroids using only the kernel
Prove: ∥ϕ(x)−ϕ(z)∥2=k(x,x)−2k(x,z)+k(z,z)\norm{\phi(\vb{x}) - \phi(\vb{z})}^2 = k(\vb{x}, \vb{x}) - 2k(\vb{x}, \vb{z}) + k(\vb{z}, \vb{z}), and the nearest-centroid rule in feature space can be evaluated using only the kernel.
0
Let k=⟨ϕ,ϕ⟩k = \inner{\phi}{\phi} and let μc=1nc∑i∈Icϕ(xi)\vb{\mu}_c = \frac{1}{n_c}\sum_{i \in I_c}\phi(\vb{x}_i) be the centroid of class cc, with indices IcI_c.

Step 1 of 4. How do you obtain distance between ϕ(x)\phi(\vb{x}) and ϕ(z)\phi(\vb{z})?

NumericA distance in feature space
With kernel k(x,z)=(xz+1)2k(x, z) = (xz + 1)^2 on R\R, class +1+1 has points 11 and 22. Compute ∥ϕ(0)−μ+∥2\norm{\phi(0) - \vb{\mu}_+}^2, squared distance between the image of x=0x = 0 and the class centroid in feature space.
QuizVery large γ
In an RBF-kernel SVM with large CC, what happens as γ→∞\gamma \to \infty?
QuizAlways a kernel?
Let k1,k2k_1, k_2 be kernels on Rd\R^d. Which functions are kernels for any k1,k2k_1, k_2?

More than one answer may be correct.

QuizMoving along the diagonal
An RBF SVM with γ=0.01\gamma = 0.01 and C=100C = 100 gives a good nearly linear boundary. By the first-order approximation, what other pair gives approximately the same classifier?
QuizWhat supports SVR?
In a trained SVR with ε>0\varepsilon > 0, which training points can have coefficient βi=αi−αi∗≠0\beta_i = \alpha_i - \alpha_i^* \neq 0?
NumericHow many points fit?
What is the largest nn for which the full float64 Gram matrix n×nn \times n fits in 32 GiB (2352^{35} bytes)?
CodeA certificate that it is not a kernel
Implement gram_min_eigenvalue(kernel, X), which constructs Gram matrix Kij=K_{ij} = kernel(X[i], X[j]) (the function takes two vectors and returns a number) and returns its smallest eigenvalue. Then assign PARAMS_SIGMOIDE a pair (a, c) for which sigmoid tanh⁡(a x⊤z+c)\tanh(a\,\vb{x}\T\vb{z} + c) has a clearly negative eigenvalue on the test points (30 uniform points in [−1,1]3[-1, 1]^3). Tests also check that RBF and polynomial kernels have no negative eigenvalues except rounding.
import numpy as np

def gram_min_eigenvalue(kernel, X):
  """Menor autovalor de la matriz de Gram K_ij = kernel(X[i], X[j])."""
  # tu código
  return 0.0

def sigmoide(a, c):
  return lambda x, z: np.tanh(a * (x @ z) + c)

# (a, c) con los que la sigmoide no es un kernel válido sobre los puntos de los tests
PARAMS_SIGMOIDE = None
Shift+Enter to run
CodeNyström features
Implement nystrom_features(X, Z, kernel, rtol=1e-10), returning a matrix F of shape (n,r)(n, r) with r≤mr \le m such that F @ F.T =KnmKmm+Kmn= \mat{K}_{nm}\mat{K}_{mm}^{+}\mat{K}_{mn}, using the eigendecomposition of Kmm\mat{K}_{mm} and discarding eigenvalues below rtol times the largest. kernel(A, B) returns the Gram matrix between rows of A and B. Tests check that you reproduce K\mat{K} on landmarks, trace error does not increase when landmarks are added and drops substantially, and repeated landmarks do not cause failure.
import numpy as np

def nystrom_features(X, Z, kernel, rtol=1e-10):
  """F (n × r) con F Fᵀ = K_nm K_mm⁺ K_mn."""
  # tu código
  return np.zeros((len(X), len(Z)))
Shift+Enter to run

Summary

Key idea
An algorithm using only inner products can run in an enormous, even infinite, feature space by replacing each product with a kernel k(x,z)k(\vb{x}, \vb{z}); a boundary linear there is curved in the original space.
  • A function is a kernel if and only if all its Gram matrices are positive semidefinite. Practically, one negative eigenvalue rules out a similarity, and new kernels are built with closure rules: sum, nonnegative scaling, product, f(x)f(z)f(\vb{x})f(\vb{z}), composition, exponential and normalization.
  • RBF has infinite-dimensional feature space and invertible Gram matrices: it can memorize any labels. γ\gamma is inverse squared length scale: γ→∞\gamma \to \infty isolates each point and γ→0\gamma \to 0 makes it linear SVM with C~=2γC\tilde C = 2\gamma C.
  • Kernel SVM is the usual dual with K\mat{K} instead of XX⊤\mat{X}\mat{X}\T and predicts using ∑i∈Sαiyik(xi,x)+b\sum_{i \in \mathcal{S}}\alpha_iy_ik(\vb{x}_i, \vb{x}) + b. SMO solves it by requesting columns of K\mat{K} from a cache; cost is between O(n2)\bigO(n^2) and O(n3)\bigO(n^3) and support-vector count grows with nn.
  • SVR uses ε\varepsilon-insensitive loss: points inside the tube do not enter the solution and ε\varepsilon controls sparsity. CC, γ\gamma and ε\varepsilon are chosen together on logarithmic grids with scaled variables.
  • Nyström replaces K\mat{K} with KnmKmm+Kmn\mat{K}_{nm}\mat{K}_{mm}^{+}\mat{K}_{mn}, projection onto the space of mm landmarks, turning the kernel method into a linear one of dimension mm. It works better when landmarks cover data better: k-means beats uniform sampling, and both beat random Fourier features at equal feature count.