Kernel SVMs: RBF, C and gamma
Points inside a ring belong to one class and points on the ring to the other. No straight line separates them, but add the feature (the squared distance from the centre) and a flat plane does. Engineering such features by hand is hard in general. The kernel trick lets an SVM work in a very large, even infinite-dimensional, feature space without ever computing the features, because the SVM's dual only needs dot products between points.
The kernel trick
In the dual problem the data appears only as , and the trained classifier is
Replace every dot product by a kernel , the dot product in some feature space , and the SVM becomes linear in that space, nonlinear in the original one:
Common kernels in scikit-learn:
| Kernel | Feature space | |
|---|---|---|
| linear | the inputs themselves | |
| polynomial | all monomials up to degree | |
| RBF (Gaussian) | infinite-dimensional | |
| sigmoid | (not always a valid kernel) |
A function is a valid kernel when every kernel matrix it produces is positive semidefinite (Mercer's condition), which keeps the dual problem convex. The theory is in The Dual SVM and Kernels and Positive Semidefinite Matrices.
The RBF kernel and its two knobs
The RBF kernel is a similarity that is 1 for identical points and decays with distance; sets how far a point's influence reaches. The decision function is a weighted sum of Gaussian bumps centred on the support vectors.
- gamma controls the bump width. Small : wide bumps, smooth boundary, close to linear. Large : narrow bumps, each support vector carves its own island; the model can memorise the training set.
- C controls how much margin violations cost, as in the linear SVM. Large : fewer training errors, more complex boundary.
Both regularise, in different ways, so they are tuned together on a logarithmic grid. In the lab, the RBF SVM starts on the circles data with , : a smooth closed boundary, 25 support vectors, 99.5 % test accuracy on 200 new points. Step up to 5 and up to 100: the margins shrink into small loops around individual support vectors, training accuracy reaches 100 % and test accuracy drops to 96.5 %. Raise the noise to its maximum as well and the boundary itself wraps single points: training accuracy stays at 100 %, test accuracy falls to 73.5 %.
Rebuilding the decision function
scikit-learn's SVC stores the support vectors, the products (dual_coef_) and (intercept_). The decision function can be recomputed from them with a ten-line RBF kernel:
import numpy as np
from sklearn.datasets import make_circles
from sklearn.svm import SVC
X, y = make_circles(n_samples=200, noise=0.1, factor=0.4, random_state=0)
def rbf_kernel(A, B, gamma):
sq = (A ** 2).sum(1)[:, None] - 2 * A @ B.T + (B ** 2).sum(1)[None, :]
return np.exp(-gamma * sq)
lin = SVC(kernel="linear", C=1.0).fit(X, y)
rbf = SVC(kernel="rbf", C=1.0, gamma=1.0).fit(X, y)
print("linear kernel training accuracy:", round(lin.score(X, y), 3))
print("RBF kernel training accuracy:", round(rbf.score(X, y), 3), " support vectors:", len(rbf.support_))
# the fitted model is f(x) = sum_i alpha_i y_i K(x_i, x) + b over the support vectors only
x_new = np.array([[0.0, 0.0], [0.9, 0.1], [0.5, -0.5]])
f_ours = rbf_kernel(x_new, rbf.support_vectors_, 1.0) @ rbf.dual_coef_[0] + rbf.intercept_[0]
print("decision values ours ", f_ours.round(4))
print("decision values sklearn", rbf.decision_function(x_new).round(4))
# the explicit feature map for circles: add r^2 = x1^2 + x2^2 and a linear SVM works
X3 = np.column_stack([X, (X ** 2).sum(axis=1)])
print("linear SVM on (x1, x2, x1^2 + x2^2):", round(SVC(kernel="linear").fit(X3, y).score(X3, y), 3))linear kernel training accuracy: 0.625
RBF kernel training accuracy: 1.0 support vectors: 38
decision values ours [ 2.4021 -1.1868 -0.1515]
decision values sklearn [ 2.4021 -1.1868 -0.1515]
linear SVM on (x1, x2, x1^2 + x2^2): 0.995
A linear SVM is barely better than guessing on the rings (0.625). The RBF SVM separates them using 38 of the 200 points as support vectors, and the hand-computed decision values match scikit-learn's exactly: the centre is firmly in the inner class (), the point on the outer ring is firmly outside. The last line is the kernel trick done by hand: one extra feature, , makes the problem linearly separable. The RBF kernel finds such a representation without being told.
Tuning C and gamma together
On noisy moons, with the scaler in the pipeline and 5-fold cross-validation on the training part only:
import numpy as np
from sklearn.datasets import make_moons
from sklearn.model_selection import GridSearchCV, StratifiedKFold, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = make_moons(n_samples=300, noise=0.3, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
pipe = make_pipeline(StandardScaler(), SVC(kernel="rbf"))
grid = {"svc__C": [0.1, 1, 10, 100], "svc__gamma": [0.1, 1, 10, 100]}
search = GridSearchCV(pipe, grid, cv=StratifiedKFold(5, shuffle=True, random_state=0)).fit(X_tr, y_tr)
scores = search.cv_results_["mean_test_score"].reshape(4, 4)
print("CV accuracy gamma=0.1 gamma=1 gamma=10 gamma=100")
for C, row in zip(grid["svc__C"], scores):
print(f"C={C:<5} " + " ".join(f"{s:.3f}" for s in row))
print("best:", search.best_params_, " test accuracy:", round(search.score(X_te, y_te), 3))
big = make_pipeline(StandardScaler(), SVC(C=100, gamma=100)).fit(X_tr, y_tr)
print("C=100, gamma=100: train", round(big.score(X_tr, y_tr), 3), " test", round(big.score(X_te, y_te), 3),
" support vectors", len(big[-1].support_), "of", len(y_tr))CV accuracy gamma=0.1 gamma=1 gamma=10 gamma=100
C=0.1 0.857 0.881 0.838 0.710
C=1 0.852 0.900 0.895 0.790
C=10 0.852 0.919 0.881 0.790
C=100 0.876 0.910 0.867 0.790
best: {'svc__C': 10, 'svc__gamma': 1} test accuracy: 0.944
C=100, gamma=100: train 1.0 test 0.9 support vectors 199 of 210
The grid has a ridge of good values around , and the best cell (, ) scores 0.944 on the 90 held-out points. The corner , shows overfitting in its purest form: every training point is classified correctly, 199 of the 210 points are support vectors (each one its own bump), and test accuracy drops. Since SVC is sensitive to the scale of the features ( multiplies squared distances), the scaler belongs in the pipeline.
Cost and scale
A kernel SVM works with the kernel matrix. Training time grows between and , and prediction costs one kernel evaluation per support vector. Up to about to rows that is fine; beyond, use a linear SVM, or approximate the kernel with explicit random features (Nystroem, RBFSampler) followed by a linear model.
Strengths, weaknesses, when to use it
Kernel SVMs give flexible boundaries with a convex training problem and few hyperparameters, and work well on small and medium data sets with many features (images of digits, spectra, bioinformatics). They scale badly with , need scaling and a , search, give no probabilities without extra calibration, and are hard to interpret. On large tabular data, gradient boosting usually wins; on very large or sparse data, linear models.
Pitfalls
- Default gamma on unscaled data.
gamma="scale"uses , which helps, but a single wide feature still dominates distances. - Searching C and gamma on a linear grid. Both act multiplicatively; use powers of 10.
probability=Truein a hurry. It runs an internal 5-fold cross-validation (slow) and its probabilities can disagree withpredict.
Practice
- For two points at distance 2, what is the RBF kernel value with and with ?
Answer
and . With the large , the two points are effectively unrelated, which is why large makes each support vector act alone.
- Why does the SVM need only the kernel, never itself?
Answer
Both the dual objective and the decision function contain the data only through dot products , and the kernel computes exactly these values from the original inputs.
Test yourself
What does increasing in an RBF SVM do?
- Widens each support vector's influence, smoother boundary
- Narrows each support vector's influence, more complex boundary
- Changes the margin penalty
- Turns the model linear
Which quantities define a trained kernel SVM's decision function?
- A weight per feature only
- The support vectors, their coefficients , the intercept and the kernel
- All training points with equal weights
- The class means
Training accuracy is 1.0, test accuracy much lower, and nearly every point is a support vector. What should you change?
- Increase gamma and C
- Decrease gamma and/or C
- Remove the scaler
- Use more support vectors