Mathematical foundations
Kernels, Gram Matrices, and Implicit Feature Spaces
Understand positive semidefinite kernels, Gram matrices, feature maps, the kernel trick, and the assumptions behind similarity-based models.
By the end you can
- Interpret a kernel as an inner product in an explicit or implicit feature space
- Explain why valid kernel Gram matrices are positive semidefinite
- Use the kernel trick to reason about nonlinear models without constructing every feature
- Recognize scaling, parameter, computational, and semantic failure modes in kernel methods
Comparison
Linear, polynomial, and radial kernels
Each family encodes a different prior about useful similarity.
The linear kernel, k(x,z)=xᵀz, works in the original feature space. It is fast and interpretable on sparse data, it is the baseline to beat before any nonlinear kernel is tried, and it is sensitive to scaling and offsets.
The polynomial kernel represents interactions up to a chosen degree. It captures multiplicative feature combinations, the degree controls complexity, the offset changes which lower-order terms are included, and its values can become numerically large.
The RBF kernel lets similarity decay with squared Euclidean distance. It creates a rich infinite-dimensional feature space, its bandwidth controls locality, it is the most sensitive of the three to feature scaling, and at extreme bandwidths its Gram matrix degenerates toward an identity-like or a nearly constant matrix.
The three families are not independent choices sitting side by side. At one end of its range, the third collapses into the first. Keerthi and Lin proved it in 2003: as σ²→∞ with C = C̃σ², the Gaussian-kernel SVM converges to the linear SVM with penalty C̃. A kernel family is a claim about which transformations should leave similarity alone. The claim is testable.
Linear kernel
k(x,z)=xᵀz.
- Uses the original feature space
- Fast and interpretable for sparse data
- Sensitive to scaling and offsets
- Baseline before nonlinear kernels
Polynomial kernel
Represents interactions up to a chosen degree.
- Captures multiplicative feature combinations
- Degree controls complexity
- Offsets change included lower-order terms
- Can become numerically large
RBF kernel
Similarity decays with squared Euclidean distance.
- Creates a rich infinite-dimensional feature space
- Bandwidth controls locality
- Highly sensitive to feature scaling
- Can become nearly identity or nearly constant
A kernel is a rule for comparing examples through geometry
A kernel k(x,z) returns a scalar similarity with special mathematical structure. When k is valid in the usual sense, there exists a feature map φ such that k(x,z)=⟨φ(x),φ(z)⟩, possibly in a very large space. Algorithms that depend only on inner products can replace explicit dot products with kernel evaluations. The resulting model is linear in feature space while it may be nonlinear in the original inputs.
What that substitution buys has been scored on a public benchmark. Shankar and colleagues stated the comparison in a single sentence in 2020: “We construct a simple neural network architecture using only 3x3 convolutions, 2x2 average pooling, ReLU, and optimized with SGD and MSE loss that achieves 96% accuracy on CIFAR10, and whose corresponding compositional kernel achieves 90% accuracy.” The kernel learns no features at all. It only compares examples, and it lands within a few points of the network it corresponds to. In the small-data regime the same paper reports that “compositional kernels outperform NTKs and neural networks outperform both kernel methods”.
A different construction shows the same gap. A depth-11 convolutional neural tangent kernel with global average pooling reached 77.43% on CIFAR-10, against 82.92% for the matching finite CNN. Arora and colleagues reported both numbers in 2019, and call the kernel result “a significant new benchmark for the performance of a pure kernel-based method on CIFAR-10”. A benchmark set, and still trailing.
The kernel trick saves feature construction, not all computation. Training still depends on a Gram matrix whose size grows with the number of examples.
A kernel hides the coordinates of a feature space while preserving its inner-product geometry.
Positive semidefiniteness makes the similarity geometrically consistent
For training points x₁,…,xₙ, the Gram matrix K has entries Kᵢⱼ=k(xᵢ,xⱼ). If k is an inner product kernel, then cᵀKc=||Σᵢcᵢφ(xᵢ)||²≥0 for every coefficient vector c. That is the positive semidefinite property, and it is what allows K to behave like inner products among feature vectors.
The condition is old enough to carry a name. James Mercer set out the theory of functions of positive type in 1909, and practitioners still speak of Mercer kernels. The condition above is his.
An arbitrary symmetric similarity matrix may fail this test. Small negative eigenvalues can arise from floating-point error or approximations. Large negative structure indicates that the similarity is not an ordinary Hilbert-space kernel. That is not a hypothetical about badly chosen functions. Chen and colleagues assembled eight real similarity datasets in 2009 — among them 213 proteins in four classes (72/72/39/30) compared by sequence alignment, 204 Amazon books by 47 authors, 945 NIST faces of 139 people, 241 patrol-unit members, and 435 Congressional voting records. Their statement of the problem is flat: “Similarity functions may be asymmetric and fail to satisfy the other mathematical properties required for metrics or inner products”.
What practitioners do about it is a small catalogue of repairs, applied to the spectrum before any kernel algorithm sees the matrix. “Spectrum clip makes S PSD by clipping all the negative eigenvalues to zero”, and “any indefinite similarity matrix can be made PSD by shifting its spectrum by the absolute value of its minimum eigenvalue”. Flipping the sign of the negative eigenvalues is the third. Each repair changes the geometry. Each is a modeling decision rather than a numerical cleanup.
The same situation holds for structured data, and Oglic and Gärtner named the part that makes it dangerous in 2019: “Such functions are typically not positive definite and it is often well beyond the expertise of practitioners to verify this condition.” Their own work is motivated by “problems with structured representations (e.g., graphs, strings, time-series)”. The check is cheap. Skipping it is what costs.
Example
Bandwidth changes the effective neighborhood
Consider an RBF kernel k(x,z)=exp(−||x−z||²/(2σ²)). Both ends of the bandwidth range were worked out analytically by Keerthi and Lin in 2003. The scikit-learn documentation states the same two failures operationally, on its RBF SVM parameters example page: “If gamma is too large, the radius of the area of influence of the support vectors only includes the support vector itself and no amount of regularization with C will be able to prevent overfitting. When gamma is very small, the model is too constrained and cannot capture the complexity or “shape” of the data.”
- Very small σ: Only near-duplicate points have substantial similarity, and the Gram matrix approaches an identity-like structure. Keerthi and Lin state the limit outright: “Since e−‖xi−xj‖2/(2σ2) → δij as σ2 → 0”. The consequence depends on the penalty. Severe overfitting “occurs in the case where σ2 → 0 and C is fixed to a sufficiently large value”, and severe underfitting when C is small instead.
- Very large σ: Most pairs look similar and the Gram matrix approaches a nearly constant matrix. The formal version of this end is a convergence, not a vague blurring: “If σ2 → ∞ and C = C̃σ2 where C̃ is fixed then the SVM classifier converges to the Linear SVM classifier with penalty parameter C̃”. The nonlinear model has quietly become the linear one you were trying to beat.
- Middle scale: Local neighborhoods can support smooth nonlinear boundaries. This is the only regime in which the kernel is doing work that neither degenerate limit can do.
- Scaling issue: A high-variance coordinate can dominate distance unless features are transformed deliberately, and the size of that effect has been measured. On svmguide1, an astroparticle-physics set of 3,089 training and 4,000 testing points with 4 features and 2 classes, default parameters give 66.925% test accuracy on the raw data and 96.15% after linearly scaling each attribute to [−1,+1]. The same parameters, the same model, thirty points of accuracy living in the preprocessing. The LIBSVM authors' own guide says it in five words: “Scaling before applying SVM is very important.” A 2025 study supplies the control across 12 scaling techniques, 14 algorithms and 16 datasets: on the Dry Bean data SVM accuracy rises from 0.5803 unscaled to 0.9268 with a robust scaler, while Random Forest barely moves, 0.9238 to 0.9226. Its conclusion is that while “ensemble methods ... demonstrate robust performance largely independent of scaling, other widely used models such as Logistic Regression, SVMs, TabNet, and MLPs show significant performance variations highly dependent on the chosen scaler”. The sensitivity belongs to distance-based kernels. That is exactly why it gets forgotten by people arriving from tree models.
- Validation: Tune bandwidth and regularization together, because locality and model flexibility interact. Keerthi and Lin's two limits are limits in σ and C jointly, not in σ alone. On svmguide1 the grid search that followed scaling added a further step, to 96.875%, by choosing C=2 and γ=2. scikit-learn describes the same geometry of the search space: “For intermediate values, we can see on the second plot that good models can be found on a diagonal of C and gamma.”
Key idea
The kernel trick can move cost from features to examples
An n×n Gram matrix requires quadratic storage and often expensive optimization, and the exponents are documented rather than folkloric. The Core Vector Machine paper opens with the statement itself, in 2005: “Standard SVM training has O(m3) time and O(m2) space complexities, where m is the training set size”. scikit-learn tells its users the same thing about the libsvm-backed SVC: “The fit time scales at least quadratically with the number of samples and may be impractical beyond tens of thousands of samples.” Then it gives the remedy: “For large datasets consider using LinearSVC or SGDClassifier instead, possibly after a Nystroem transformer or other Kernel Approximation.” Its user guide brackets the solver: “The QP solver used by the libsvm-based implementation scales between O(n_features × n_samples^2) and O(n_features × n_samples^3) depending on how efficiently the libsvm cache is used in practice (dataset dependent).”
Tens of thousands of samples is a low ceiling for a modern dataset. Rahimi and Recht put the consequence in wall-clock terms in 2007: “For example, even with the most powerful workstation, it might take days to train a nonlinear SVM on a dataset with half a million training examples.” Their proposal was to stop computing the kernel exactly: “To accelerate the training of kernel machines, we propose to map the input data to a randomized low-dimensional feature space and then apply existing fast linear methods.”
Their Table 1 is the reason an approximation cannot be judged on speed alone. The benchmark is forest cover type, 522,000 instances in 54 dimensions — the same set the Core Vector Machine paper lists as “forest cover type 522,911 [patterns], 54 [features]”. Exact libSVM reached 2.2% test error in 44 hours. The Core Vector Machine reached 2.3% in 7.5 hours. Binning features reached the identical 2.2% in 25 minutes. Fourier random features with D=5000 ran in 71 minutes and lost the accuracy: 11.6%. The fast family and the accurate family were not the same family, in one table, on one dataset. Rahimi and Recht's own summary is that their features “compete favorably in speed and accuracy with state-of-the-art kernel-based classification and regression algorithms” — a claim about a pair of numbers, not one of them.
Approximate features, landmark methods, sparse solvers, and random Fourier features all reduce cost by replacing the full kernel matrix with a lower-dimensional approximation. The landmark route has a name and a proof. Williams and Seeger brought the Nyström method to kernel machines in 2000, “by carrying out an eigendecomposition on a smaller system of size m < n, and then expanding the results back up to n dimensions”. Drineas and Mahoney supplied the error analysis five years later: “We develop and analyze an algorithm to compute an easily-interpretable low-rank approximation to an n × n Gram matrix G such that computations of interest may be performed more rapidly.” They open on the motivation — “A problem for many kernel-based methods is that the amount of computation required to find the solution scales as O(n3), where n is the number of training examples” — and prove that sampling O(k/ε⁴) columns suffices to come within ε·Σᵢ₌₁ⁿ Gᵢᵢ², epsilon times the sum of the squared diagonal entries, of the best rank-k approximation, in both spectral and Frobenius norm. That is what a quantified shortcut looks like.
The ceiling can be broken outright. The Core Vector Machine paper reports that “CVM with the Gaussian kernel produces superior results on the KDDCUP-99 intrusion detection data, which has about five million training patterns, in only 1.4 seconds on a 3.2GHz Pentium–4 PC”. Fastfood reports the same shape of trade in 2013: “Experiments show that we achieve similar accuracy to full kernel expansions and Random Kitchen Sinks while being 100x faster and using 1000x less memory.”
At the research end the bill is still paid in full. Shankar and colleagues, building compositional kernels for image benchmarks, record that “Even with this constraint, the largest compositional kernel matrices we study took approximately 1000 GPU hours to compute.” The fitting afterwards is a second exponent: “Once a kernel matrix is constructed, exact minimization of empirical risk often scales as O(N3)”. Judge an approximation against prediction, calibration, memory, and latency rather than matrix error alone. On forest cover type, 2.2% at 25 minutes and 11.6% at 71 minutes were both approximations of the same kernel.
Implicit features are not free: 44 hours of exact libSVM against 25 minutes of binned features at the identical 2.2% error, and 11.6% for the approximation that was slower than both.
Steps
A kernel-selection audit
Treat the kernel as a representation choice with testable invariances.
1. Define useful similarity. State which transformations should preserve or reduce similarity. This is domain work, not mathematics: sequence alignment for proteins, co-authorship for books and pairwise ratings for faces gave Chen and colleagues eight different answers across eight datasets.
2. Standardize the inputs. Align distance scales with the task before evaluating kernels. On svmguide1 that one step moved default-parameter accuracy from 66.925% to 96.15%, and the LIBSVM guide puts it ahead of parameter selection for exactly that reason.
3. Verify kernel structure. Check symmetry and positive semidefinite Gram behavior. Decide in advance which repair — clip, flip or shift — you will apply if the spectrum comes back indefinite, because each of the three changes the geometry differently.
4. Tune jointly. Select kernel parameters and regularization under leak-free validation. Keerthi and Lin's two limits are limits in σ and C together, and the empirical picture matches: the good models lie on a diagonal in (C, γ), so a search that fixes one parameter and sweeps the other can miss them entirely.
5. Inspect scalability and neighbors. Review concrete similar pairs, memory cost, and approximation error. Prefer a method whose error is bounded, such as the Nyström construction Drineas and Mahoney analyzed, over a shortcut whose only measured property is its speed.
1. Define useful similarity
State which transformations should preserve or reduce similarity.
2. Standardize the inputs
Align distance scales with the task before evaluating kernels.
3. Verify kernel structure
Check symmetry and positive semidefinite Gram behavior.
4. Tune jointly
Select kernel parameters and regularization under leak-free validation.
5. Inspect scalability and neighbors
Review concrete similar pairs, memory cost, and approximation error.
Visual
From inputs to a kernel model
The feature map may remain implicit throughout the computation.
1. Original input x. Examples begin in a space where the desired boundary may be nonlinear.
2. Feature map φ(x). A conceptual transformation creates coordinates where linear comparison is useful; for the RBF kernel that space is infinite-dimensional and is never written down.
3. Kernel evaluation. Compute inner products k(x,z) without necessarily constructing φ.
4. Gram matrix K. Store pairwise kernel values for the training examples. This is the step with a price tag. Shankar and colleagues built theirs over CIFAR-10 and CIFAR-100 (60,000 images of 32×32×3) and MNIST (70,000 images of 28×28), “creating a total complexity of Õ(N2D2)”. They spell out what enlarging the training set does to it: “if one wants to perform 100 augmentations per example, then the final kernel matrix will be 10,000 times larger, and solving the prediction problem may be one million times slower”. The neural tangent kernel carries a matching count: “To compute the CNTK matrix corresponding to a CNN with GAP that has L convolution layers and one fully-connected layer on n samples, the time complexity is O(n2P2Q2L)”. Sixty thousand images and roughly a thousand GPU hours pass before a single prediction is made.
5. Kernel predictor. Express predictions through weighted similarities to training examples.
1. Original input x
Examples begin in a space where the desired boundary may be nonlinear.
2. Feature map φ(x)
A conceptual transformation creates coordinates where linear comparison is useful.
3. Kernel evaluation
Compute inner products k(x,z) without necessarily constructing φ.
4. Gram matrix K
Store pairwise kernel values for the training examples.
5. Kernel predictor
Express predictions through weighted similarities to training examples.
Kernelization changes the representation used by an inner-product algorithm.
Key takeaways
- A kernel computes an inner product in an explicit or implicit feature space, and such a predictor reaches 90% on CIFAR-10 where the corresponding network reaches 96% (Shankar and colleagues, 2020).
- The kernel trick lets inner-product algorithms use nonlinear representations without materializing every feature, but it relocates the cost rather than removing it: the bill arrives as the Gram matrix.
- Valid Gram matrices are positive semidefinite because their quadratic forms are squared feature-space norms; applied similarity matrices frequently are not, and get repaired by clipping, flipping or shifting the spectrum (Chen and colleagues, 2009).
- Kernel parameters define invariances and locality: scaling svmguide1 moved accuracy from 66.925% to 96.15% at unchanged default parameters, and Keerthi and Lin's σ→0 and σ→∞ limits show why C and σ must be chosen together.
- Exact kernel training costs O(m³) time and O(m²) space in the training set size (Tsang and colleagues, 2005), which scikit-learn restates for practitioners as impractical beyond tens of thousands of samples.
- Mathematical validity does not guarantee useful similarity, and speed does not guarantee accuracy: on forest cover-type, 25 minutes at 2.2% error and 71 minutes at 11.6% were two approximations of the same kernel (Rahimi and Recht, 2007).