Sub topic 9
The kernel trick: nonlinear boundaries without explicit features
This chapter assumes you know the soft-margin SVM, the dual problem, and support vectors from the earlier chapters. You should also be comfortable with dot products and NumPy. Here you will see why the dual form lets an SVM draw curved boundaries without ever building the features that make them straight.
The problem: classes that no line separates
A linear SVM draws a hyperplane in the input space. If one class forms a ring around another, no hyperplane separates them. The classical fix is a feature map φ that sends each point x into a higher-dimensional space where a hyperplane does work. For two inputs, φ(x) = (x₁², √2·x₁x₂, x₂²) turns circular and elliptical boundaries into planes.
The cost is that the number of features grows quickly with input dimension and polynomial degree. For the RBF kernel, the feature space has infinitely many dimensions, so you cannot build it at all.
Why the dual form removes the cost
In the dual problem, the training data appears only through dot products xᵢ·xⱼ. The prediction for a new point x has the same property:
f(x) = Σᵢ αᵢ yᵢ (xᵢ · x) + b
The sum runs over support vectors, since all other αᵢ are zero. If you map to feature space, every dot product becomes φ(xᵢ)·φ(x). A kernel function computes that value directly from the original inputs:
K(x, z) = φ(x) · φ(z)
Replace each dot product in the dual with K, and you train and predict in feature space without computing φ. This substitution is the kernel trick. The nonlinear decision function becomes:
f(x) = Σᵢ αᵢ yᵢ K(xᵢ, x) + b
Checking the identity numerically
For the degree-2 map above, the kernel is K(x, z) = (x·z)². The code below computes both sides.
import numpy as np
def phi(v):
return np.array([v[0] ** 2, np.sqrt(2) * v[0] * v[1], v[1] ** 2])
x = np.array([1.0, 2.0])
z = np.array([3.0, -1.0])
explicit = phi(x) @ phi(z) # dot product in 3-D feature space
kernel = (x @ z) ** 2 # computed in the original 2-D space
print(explicit, kernel)
print(np.isclose(explicit, kernel))Both values are 1.0. The kernel needs one 2-D dot product and one squaring. The explicit route builds two 3-D vectors first. In higher dimensions and degrees, this gap grows enormously.
What a kernel must satisfy
Not every function of two points is a valid kernel. K must correspond to a dot product in some feature space. Mercer's condition states the requirement: for any finite set of points, the Gram matrix Kᵢⱼ = K(xᵢ, xⱼ) must be symmetric and positive semi-definite.
This matters because the dual stays a convex problem only when the Gram matrix is positive semi-definite. A function that violates the condition can produce a non-convex objective, and solvers may fail to converge or return poor solutions. The sigmoid kernel, tanh(γ x·z + r), is the usual example. It is not positive semi-definite for all parameter choices.
Valid kernels can be combined. Sums and products of valid kernels are valid, and so are positive scalings. This lets you build kernels for strings, graphs, or other structured data, as long as the combination stays positive semi-definite.
Seeing it work in scikit-learn
The next example fits a linear and an RBF SVM to concentric circles. It then rebuilds the RBF decision function by hand from the stored dual coefficients.
import numpy as np
from sklearn.datasets import make_circles
from sklearn.metrics.pairwise import rbf_kernel
from sklearn.svm import SVC
X, y = make_circles(n_samples=300, factor=0.4, noise=0.1, random_state=0)
linear = SVC(kernel="linear").fit(X, y)
rbf = SVC(kernel="rbf", gamma=1.0).fit(X, y)
print("linear accuracy:", linear.score(X, y))
print("rbf accuracy:", rbf.score(X, y))
# Rebuild f(x) = sum_i alpha_i y_i K(x_i, x) + b by hand
K = rbf_kernel(X[:5], rbf.support_vectors_, gamma=1.0)
manual = K @ rbf.dual_coef_.ravel() + rbf.intercept_[0]
print(np.allclose(manual, rbf.decision_function(X[:5])))The linear model scores near chance. The RBF model scores close to 1.0. The final line prints True: scikit-learn's dual_coef_ stores the products αᵢyᵢ, so the manual sum matches decision_function exactly.
Consequences of working in the dual
Three practical points follow from the kernelized form.
- No weight vector. For a nonlinear kernel, w lives in feature space and may be infinite-dimensional.
coef_exists only forkernel="linear". You inspect a nonlinear model throughsupport_vectors_anddual_coef_. - Prediction cost depends on support vectors. Each prediction evaluates K against every support vector. A model with 5,000 support vectors costs 5,000 kernel evaluations per query. A linear model costs one dot product.
- Training cost depends on pairs of points. The solver works with the n × n Gram matrix, or a cached part of it. Training time grows faster than linearly with n, and memory pressure appears long before it does for linear models.
Common kernels at a glance
| Kernel | Formula | Implicit feature space | Main parameters |
|---|---|---|---|
| Linear | x·z | Original inputs | none |
| Polynomial | (γ x·z + r)^d | All monomials up to degree d | degree d, γ, r |
| RBF | exp(−γ‖x − z‖²) | Infinite-dimensional | γ |
A later chapter compares these choices. The point here is that all three plug into the same dual solver.
Precomputed kernels
If your similarity measure has no built-in option, you can supply the Gram matrix yourself with kernel="precomputed". For training, pass the n × n matrix. For prediction, pass a matrix of shape (ntest, ntrain), with each row holding kernel values against all training points. Passing a matrix with the wrong shape is a frequent error. Scaling the raw data does not help when you supply the Gram matrix, so apply scaling before you compute it.
Common errors
- Reading
coef_on a non-linear model. It raises an error. Usedual_coef_instead. - Using a kernel that is not positive semi-definite and expecting stable training.
- Passing the training Gram matrix at prediction time with
kernel="precomputed". Prediction needs kernel values between test and training points. - Assuming a more powerful kernel is always better. A very flexible kernel can fit noise, which later chapters handle through C and gamma.
Exercise
A degree-2 polynomial kernel K(x, z) = (x·z)² is used on 1,000-dimensional inputs. Why is it cheaper to evaluate the kernel than to build the explicit feature map, and what does prediction cost depend on afterwards?
Show answer
The kernel needs one 1,000-dimensional dot product followed by a squaring. The explicit map has about 500,000 monomial features (all pairwise products of the 1,000 inputs, with repeats), which must be built for every point before the dot product. Prediction then evaluates K between the new point and each support vector, so its cost grows with the number of support vectors.
Exercise
You call SVC(kernel="rbf").fit(X, y) and then read model.coef_. What happens, and how can you inspect the fitted model instead?
Show answer
Scikit-learn raises an AttributeError, because coef_ is defined only for the linear kernel. For an RBF model the weight vector lives in an infinite-dimensional feature space. Use support_vectors_ and dual_coef_ (which holds αᵢyᵢ) together with intercept_, or call decision_function.