What is kernel method?
Kernel methods are machine learning algorithms that learn non-linear patterns by implicitly mapping inputs into a high- or infinite-dimensional Reproducing Kernel Hilbert Space (RKHS) using a positive semi-definite kernel function. Via the kernel trick, algorithms evaluate pairwise inner products in the transformed space directly in input space without explicitly computing high-dimensional feature coordinates. Classic examples include kernel Support Vector Machines, Gaussian Processes, Kernel Ridge Regression, and Kernel PCA.
Study Card: Kernel Methods
Direct Answer
Kernel methods are algorithms that operate implicitly in a high-dimensional (possibly infinite-dimensional) feature space without ever forming the transformed feature vector explicitly. Any algorithm that depends on data points only through pairwise inner products can be “kernelized” via the kernel trick using a symmetric positive semi-definite kernel function (by Mercer’s theorem):
For example, the Radial Basis Function (RBF / Gaussian) kernel corresponds to an infinite-dimensional feature mapping, yet requires only arithmetic per pair to evaluate. By the Representer Theorem, optimal solutions in regularized empirical risk minimization take the dual form . Common kernel methods include SVMs, Gaussian Processes, Kernel Ridge Regression, and Kernel PCA.
Key Terms
- Kernel Function: A symmetric positive semi-definite function whose Gram matrix is positive semi-definite, guaranteeing a valid inner product in an RKHS.
- Kernel Trick: Replacing explicit dot products with to avoid computing high-dimensional feature vectors directly.
- Reproducing Kernel Hilbert Space (RKHS): The implicit inner-product function space induced by .
- Representer Theorem: Shows that the minimizer of a regularized empirical loss over an RKHS can be written as a finite linear combination of kernels centered on the training points.
- Support Vector Machine (SVM): A maximum-margin classifier/regressor whose dual optimization relies solely on kernel evaluations between training instances.
Example
Consider the two-moons dataset in 2D, where no straight line can separate the two classes. An RBF-kernel SVM implicitly maps each 2D point into an infinite-dimensional feature space where a linear separating hyperplane exists. Projected back into the original 2D space, that hyperplane traces a smooth non-linear decision boundary tightly wrapping both interleaving crescents. (Note that while kernels work well on structured tabular data or learned embeddings, deep CNNs outperform raw-pixel RBF kernels on natural images because pixel-wise Euclidean distances are fragile to translations and lighting.)
Code Implementation
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets, svm
from sklearn.model_selection import train_test_split
# Load non-linearly separable two-moons dataset
X, y = datasets.make_moons(n_samples=200, noise=0.12, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42
)
# Train an RBF-kernel SVM
clf = svm.SVC(kernel="rbf", gamma="scale", C=1.0)
clf.fit(X_train, y_train)
print(f"RBF SVM test accuracy: {clf.score(X_test, y_test):.3f}")
print(f"Number of support vectors: {len(clf.support_)}")
# Plot decision boundary
x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
fig, ax = plt.subplots(figsize=(7, 5))
ax.contourf(xx, yy, Z, cmap=plt.cm.coolwarm, alpha=0.75)
ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=plt.cm.coolwarm, s=25, edgecolors="k", label="Train")
ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=plt.cm.coolwarm, s=35, marker="^", edgecolors="k", label="Test")
ax.set_xlabel("x1")
ax.set_ylabel("x2")
ax.set_title("Decision Boundary of RBF-Kernel SVM")
ax.legend()
plt.show()
Related Concepts
- Support Vector Machines (SVMs): Learn sparse dual weights where only support vectors near the margin contribute to predictions.
- Gaussian Processes (GPs): Non-parametric Bayesian models using a kernel function as the prior covariance matrix over functions, yielding uncertainty estimates alongside predictions.
- Kernel PCA: Diagonalizes the centered Gram matrix to extract non-linear principal components.
- RBF Kernel Hyperparameter (): Larger narrows each kernel’s radius, producing complex wiggly boundaries (higher variance); smaller produces smoother boundaries (higher bias).
- Scaling & Curse of Dimensionality Caveats: Although the kernel trick makes computation independent of the implicit feature dimension , forming and solving exact Gram matrices scales at memory and time in the sample count (motivating approximations like Random Fourier Features and the Nyström method). Moreover, distance-based kernels like RBF still suffer statistically in high-dimensional input spaces when many irrelevant features dilute pairwise Euclidean distances.