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
- 11SVM dual problemSoft-margin SVMSupport vectorsSequential minimal optimizationBasis function expansionk-nearest neighborsRegression loss functionsGrid search
- 02Positive definite matrixSpectral theoremCholesky decompositionMoore-Penrose pseudoinverse
- 09Flop counting
- 06Quadratic programmingLagrange dual function
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 with map into a larger feature space and fit a linear model there. With , 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 . All monomials through degree 3 of a vector in have 176 851 coordinates; through degree 5 of an MNIST image (), about . Explicitly constructing quickly becomes impossible. The saving observation is that many algorithms never inspect coordinates of : they use only inner products . For certain this product takes operations via a closed formula 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 , data need not be vectors. A similarity function behaving like an inner product suffices:
- Strings. The spectrum kernel counts shared length- fragments of two sequences: , with the number of occurrences of fragment in . 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. is the inner product of indicator vectors of and .
- 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 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
For the ‘Signo de ’ data, the ideal boundary is the pair of lines , a degenerate conic; SVM finds a nearby hyperbola (), possible only because includes coordinate . Two more lessons from the figure. First, a classifier linear in space has, in the original space, boundary level set . With quadratic , a conic; cubic , a cubic; Gaussian kernel, almost any curve. Second, in degree-2 mode the ‘ and ’ readout gives the same number, but SVM never built : it worked only with . Explicit is used only for drawing.
The kernel trick
Matrix with is the data Gram matrix. A kernelized algorithm sees only in training and vectors when predicting. Which admit this? Those writable using inner products whose solution is a linear combination of : 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 is no accident: for every empirical-loss minimization plus an increasing penalty on , the representer theorem guarantees it.
The polynomial kernel, coordinate by coordinate
In , expand :
The is essential: the cross term appears twice in the expansion and its weight is shared between and . The same argument works generally using the multinomial theorem.
Proof
. By the multinomial theorem, , with . With , each summand is . The number of vectors summing to equals the ways of distributing balls among boxes, (stars and bars). If , cancels every term with , leaving distributions of balls among boxes.
∎Coordinates of are, up to weights, all monomials of degree at most in . Constant controls relative degree weights: a degree- monomial has factor , so large favors lower degrees. Computing costs ; computing explicitly costs .
Distances and centroids in feature space
The trick is not limited to inner products: anything expressed with them can be computed. Distance, for example:
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 to the class with nearest centroid . The centroid lives in and need not be constructed because inner-product linearity gives
The first term is common to both classes and cancels in comparison. The remainder has a clear interpretation: the rule compares ’s average similarity to each class, corrected for class “cohesion,” . Subtracting distances gives rule with
with : a linear classifier in whose weight vector is a combination of with coefficients . With a Gaussian kernel, is, up to a constant, a kernel density estimate of class : the classifier compares estimated densities with correction , penalizing the more concentrated class. Every training point enters ; as you will see, SVM keeps only a few.
A warning the final guided exercise will check: centroid is not the image of the data mean, , unless is linear. Generally there may not even be an with (the preimage problem).
From scratch: polynomial kernel and centroid classifier
The first cell constructs the theorem’s explicit with combinations_with_replacement (each combination of indices from with repetition is an ), checks it reproduces the kernel, and measures cost.
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 and , already has 176 851 coordinates, and with and , more than two trillion. For , 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 .
The second cell implements common kernels vectorized (no loops, using identity ) and the centroid classifier using only kernel evaluations, testing it on concentric rings.
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 reaches 98.1 %, and RBF or Laplacian reaches 99.8 %. The algorithm is identical in all four rows; only changed.
Valid kernels in practice
Not every two-argument function is a kernel. Checking the definition requires finding , not always easy. Fortunately a criterion examines only finite matrices.
Proof
The first part is one line: . 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 is positive semidefinite, by the spectral theorem vectors satisfy .
∎The practical test: generate points, compute the Gram matrix and inspect its minimum eigenvalue. One (clearly beyond rounding) certifies is not a kernel: if is its eigenvector, , which would be the squared norm of . 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 , or low-rank polynomial) gives eigenvalues on the order of , and tolerance should be relative to . 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) concatenate, . (2) . (3) Tensor product: , with coordinates all products , satisfies (in matrix terms, the Schur product theorem: elementwise product of two positive-semidefinite matrices is positive semidefinite). (4) , valued in . (5) . (6) Induct using (1), (2), (3), plus constant , which is (4) with constant . (7) ; each partial sum is a kernel by (6), and if for every , the limit is also . (8) Apply (3) to and the kernel from (4) with ; geometrically .
∎These rules produce the most used kernel. Expand squared distance:
The last factor is an exponential of a scaled linear kernel (rules 2 and 7), and the first two are with (rule 4); the product is a kernel by rule 3. In fact it is exactly the normalization (rule 8) of .
These are common kernels and their construction rules, with each similarity’s meaning:
| Kernel | Parameters | What it measures | |
|---|---|---|---|
| Linear | the usual linear model | ||
| Polynomial | , | , | interactions of up to variables |
| Gaussian (RBF) | closeness at scale | ||
| Laplacian | closeness, with less smooth functions | ||
| Intersection | , | histogram overlap | |
| Spectrum | length | fragments shared by two strings | |
| Sets | common elements |
Intersection is valid because for : an inner product in of indicator functions, summed coordinate by coordinate (rule 1).
What is not a kernel
Validity matters for a concrete reason. The SVM dual minimizes with , positive semidefinite if and only if is. If has a negative eigenvalue, the objective is no longer convex: local optima may not be global, and in SMO pair curvature , which with a valid kernel is , can be negative. “Distances” can also be negative, and feature-space geometry disappears.
What you should have found:
- Sigmoid is not generally positive semidefinite. With and the initial 20 points, 8 of 20 eigenvalues are negative and the smallest is ; parameters working on every point set are hard to find. Closure rules do not justify it: with , has a Taylor series with alternating signs (), and with the coefficient of in , , 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 becomes invalid. subtracts a kernel. With two points of , and , the Gram matrix is , determinant .
- 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 . By contrast 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 for .
- 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 have norm 1 and lie on a sphere), and decays to 0 with distance, so distant points have almost orthogonal .
Infinite dimension
In one dimension, the earlier factorization and exponential series give an explicit :
There is a coordinate for each degree: feature space is infinite-dimensional, containing polynomials of all degrees with weights decreasing as . No finite can reproduce it, as the next result states precisely.
Proof
The characteristic function of is . With ,
If it were , since Gaussian density is positive throughout and is continuous, . Choose a direction with distinct projections (each pair excludes only hyperplane ). Then , and its derivatives at yield for : a Vandermonde system with distinct nodes whose only solution is . The last assertion follows because with has rank .
∎This proof previews two m13 ideas. Writing the kernel as an expectation over frequencies is Rahimi and Recht’s random-features model: sampling gives an approximate finite . And invertibility of has an immediate practical consequence: for any labels a combination interpolates them (solve ). An RBF-kernel model can memorize any training set; regularization, i.e. , prevents it.
γ as length scale and the two limits
sets the distance at which points stop resembling one another: when . Its two extremes explain most tuning behavior.
- . For distinct points : each resembles only itself. An SVM with turns the whole training set into support vectors and decision function equals once 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 (with and large , the dual gives with : the majority class). Pure memorization.
- . Every point resembles every other: , a rank-1 matrix. But the model does not degenerate to a constant: to first order , and the hyperparameter section shows the resulting SVM is linear with effective .
Between them is a band of useful values, whose location depends on data scale. Thus is meaningless without standardizing variables: if one is measured in meters and another in millimeters, the latter dominates and 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 , and prediction through . Replacing these products by applies the trick.
This is linear SVM in , with 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, depending only on supports. The only change is can no longer be stored: support vectors and their must be stored.
With length scale is , 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 toward to , depending on , merges islands into two regions following the moons. Lowering further to 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 , and pair curvature is
Cost changes. Each step updates of points with columns and of , and with a nonlinear kernel there is no explicit summarizing data: each uncached column costs kernel evaluations, . The full matrix needs float64 bytes: 80 GB for . 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 that have stayed at a bound for many iterations.
The next cell takes previous-lesson SMO and replaces 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.
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 , 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 evaluations, because SMO usually revisits indices.
Kernel SVM cost
- Memory. Full Gram matrix uses bytes. With bounded cache memory is plus cache, but each cache miss costs .
- Training. Each SMO iteration costs plus cache misses, and iteration count depends on the problem and and grows with : total is usually between and , depending on class separability, and cache capacity. You will measure this in the Nyström section.
- Prediction. per point: evaluate the kernel against each support vector. And grows with . 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 -insensitive loss, which does not penalize small residuals:
a variant of the first lesson’s regression losses: absolute loss with a dead zone of width around zero.
Geometrically SVR seeks the flattest function (smallest ) whose tube contains data, paying per unit a point protrudes. The dual follows as in SVM, with two multipliers per point, one per tube side.
Complementary slackness explains sparsity. requires the first constraint active, : the point lies at or above the tube’s upper edge. Likewise and the lower edge. Hence:
- inside the tube, : and the point does not enter ;
- on the boundary, : ;
- outside, : forces and .
Also if : both constraints active simultaneously would require . The solution depends only on points on or outside the tube, and controls how many.
Initially (, , ), 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 : its pull is bounded, so SVR, like its underlying absolute loss, is robust. Lowering reduces that pull further, at the cost of many normal points also outside (with , 28 of 41). With 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 variables and the analytic gradient, comparing to SVR.
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 and the 21 support vectors at least . The solution matches SVR to . The final table shows sparsity: with all 50 points are support vectors, with (on the order of noise deviation) 21, and with 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 explains why.
Proof
With and , the dual quadratic term is
The first two terms vanish by constraint . With substitution , the dual becomes with : the linear SVM dual with , multiplied by a positive constant that does not change the maximizer. The decision transforms similarly: , where constant terms in vanish by the same constraint, leaving plus a constant.
∎Keerthi and Lin (2003) rigorously study these limits (including very large and ) and derive a practical consequence: after a full search over 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- region the model depends only on product , so on axes equal-quality curves are lines of slope . Lower tenfold and raise tenfold to retain the model. Outside that region the exact relation changes but compensation persists: larger makes the function more flexible and calls for smaller to restrain it. Tuning with fixed and then with fixed traverses a cross and misses the diagonal. A joint logarithmic grid works: Hsu, Chang and Lin’s practical guide recommends first scaling variables (to or ), starting with and , then refining around the best point.
First, why scale. The breast_cancer dataset has variables with standard deviations between and .
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", using variance of all entries of , sets a reasonable global scale but cannot correct differing variable scales.
Now the grid. With comparable variable scales, a grid search over on noisy two moons:
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: , , , , . At lower left, small and make the model nearly linear, achieving 0.78–0.85. At right, with , no exceeds 0.84: cannot fix memorization. The best cell, and , lies at the edge of the grid, requiring expansion in a real search; here the band already shows nearly as good cells with moderate .
Notice the band’s slope: between and , whenever multiplies by the best divides by about 30; between and , about 6. The proposition’s slope would divide by and need not hold here: with and data occupying roughly three units, is no longer small and the model is truly nonlinear. The proposition describes the small- corner, where the final cell check is striking: with and , RBF SVM and linear SVM with 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 (), agreement falls to 88 %. With the approximation no longer holds (89.2 % agreement). Across the grid the diagonal shape remains: and compensate, so must be searched together.
SVR’s grid has a third dimension , measured in units of . Two practical rules: standardize too (or scale by its deviation), and search on the order of noise standard deviation, estimable from residuals of a first fit. With 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 by that rule, search and refine last, or use logarithmic-scale random search.
Scaling to many data points: Nyström approximation
A kernel SVM needs Gram matrix in some form, and with the full float64 matrix already occupies 80 GB. Williams and Seeger’s (2001) idea, used on USPS and abalone with without significant accuracy loss, approximates by a rank- matrix built from only columns.
With these, any kernel method becomes the corresponding linear method on features: kernel SVM becomes linear SVM on . What exactly is approximated?
Proof
with solving normal equations , where ; one solution is because lies in the image of : if , then and , so is orthogonal to the null space of symmetric . Projection is unique even if is not. Since is self-adjoint and idempotent, . (1) For , is already in the subspace and . (2) , a kernel (for map ). Equivalently is the Schur complement of in the joint landmark-and-data Gram matrix.
∎The theorem locates approximation failure: points whose image is far from the landmark space. With RBF this literally means far from all landmarks, because for each . Hence selection matters:
- Uniform sampling of 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.
With uniform sampling, most landmarks fall in dense regions and sparse moon tips remain gray: there 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 between 30 and 40. Notice the map too: error concentrates in blocks, rows and columns of poorly covered points.
From scratch
Implementation is short: eigendecompose , discard near-zero eigenvalues (repeated or very close landmarks make numerically singular), and multiply. Error is measured by trace, which since is positive semidefinite is also its nuclear norm and costs : .
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 , 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 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 frequencies and phases , and use , 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 , 0.42 versus 0.008. Fourier error falls slowly at the Monte Carlo average rate (0.39 with , 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 ’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 for , for decomposition and for multiplication; memory is . Linear SVM over features costs about per epoch and prediction per point , independent of . The next cell measures growth with 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 , and compares exact SVC, your k-means Nyström, scikit-learn Nystroem (uniform landmarks) and RBFSampler (random Fourier), all with LinearSVC on top.
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))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 , from 407 with 1000 points to 6983 with 20 000, always 35–41 % of data, and training time grows much faster than : 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 also reach that ceiling in this two-dimensional problem; with 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
| Class | Purpose | Important 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), NuSVR | SVR and | scale or ; support_, dual_coef_ |
SVC(kernel="precomputed") | SVM with your Gram matrix | fit(K_train, y), predict(K_test_train) with shape |
SVC(kernel=funcion) | kernel as Python function | receives two matrices and returns their Gram |
Nystroem(kernel, gamma, n_components) | Nyström features with uniform points | chain with LinearSVC, SGDClassifier or Ridge |
RBFSampler(gamma, n_components) | random Fourier for RBF | no 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.
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 , where the motif dilutes among 16 background fragments; 0.895 with , and 0.985 with , where the kernel compares exactly the discriminating fragment and SVM finds it without being told which. Notice cost: with , 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- RBF. With large , coordinates no longer fit in a dense matrix, but each length- sequence contains only fragments: serious implementations compute with sparse structures or suffix trees, never constructing the count vector.
Typical mistakes
Exercises
Step 1 of 4. How do you start?
Step 1 of 4. How do you obtain distance between and ?
More than one answer may be correct.
gram_min_eigenvalue(kernel, X), which constructs Gram matrix 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 has a clearly negative eigenvalue on the test points (30 uniform points in ). 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 = Nonenystrom_features(X, Z, kernel, rtol=1e-10), returning a matrix F of shape with such that F @ F.T , using the eigendecomposition of 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 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)))Summary
- 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, , composition, exponential and normalization.
- RBF has infinite-dimensional feature space and invertible Gram matrices: it can memorize any labels. is inverse squared length scale: isolates each point and makes it linear SVM with .
- Kernel SVM is the usual dual with instead of and predicts using . SMO solves it by requesting columns of from a cache; cost is between and and support-vector count grows with .
- SVR uses -insensitive loss: points inside the tube do not enter the solution and controls sparsity. , and are chosen together on logarithmic grids with scaled variables.
- Nyström replaces with , projection onto the space of landmarks, turning the kernel method into a linear one of dimension . It works better when landmarks cover data better: k-means beats uniform sampling, and both beat random Fourier features at equal feature count.