TExcelTAD
Home › Classical ML Algorithms: Supervised & Unsupervised › Kernel SVMs: RBF, C and gamma

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 x12+x22x_1^2 + x_2^2 (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 xi⊤xj\mathbf{x}_i^\top \mathbf{x}_j, and the trained classifier is

f(x)=∑i∈SVαiyi xi⊤x+b.f(\mathbf{x}) = \sum_{i \in \text{SV}} \alpha_i y_i \, \mathbf{x}_i^\top \mathbf{x} + b .

Replace every dot product by a kernel K(x,x′)=ϕ(x)⊤ϕ(x′)K(\mathbf{x}, \mathbf{x}') = \boldsymbol{\phi}(\mathbf{x})^\top \boldsymbol{\phi}(\mathbf{x}'), the dot product in some feature space ϕ\boldsymbol{\phi}, and the SVM becomes linear in that space, nonlinear in the original one:

f(x)=∑i∈SVαiyi K(xi,x)+b.f(\mathbf{x}) = \sum_{i \in \text{SV}} \alpha_i y_i \, K(\mathbf{x}_i, \mathbf{x}) + b .

Common kernels in scikit-learn:

Kernel K(x,x′)K(\mathbf{x}, \mathbf{x}') Feature space
linear x⊤x′\mathbf{x}^\top \mathbf{x}' the inputs themselves
polynomial (γ x⊤x′+r)d(\gamma\, \mathbf{x}^\top \mathbf{x}' + r)^d all monomials up to degree dd
RBF (Gaussian) exp⁡(−γ∥x−x′∥2)\exp(-\gamma \lVert \mathbf{x} - \mathbf{x}' \rVert^2) infinite-dimensional
sigmoid tanh⁡(γ x⊤x′+r)\tanh(\gamma\, \mathbf{x}^\top \mathbf{x}' + r) (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; 1/γ1/\gamma 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 γ\gamma: wide bumps, smooth boundary, close to linear. Large γ\gamma: 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 CC: 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 C=1C = 1, γ=1\gamma = 1: a smooth closed boundary, 25 support vectors, 99.5 % test accuracy on 200 new points. Step γ\gamma up to 5 and CC 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 %.

−2−1012−2−1012feature x₁feature x₂RBF SVM on circlesC = 1, γ = 1: 25 support vectorsclass Aclass Bdecision boundarysupport vectormarginTraining accuracy79/8098.8 %Test accuracy199/20099.5 %Test set: 200 new points

Rebuilding the decision function

scikit-learn's SVC stores the support vectors, the products αiyi\alpha_i y_i (dual_coef_) and bb (intercept_). The decision function can be recomputed from them with a ten-line RBF kernel:

python · try it yourself
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 (0,0)(0, 0) is firmly in the inner class (f=2.40f = 2.40), the point (0.9,0.1)(0.9, 0.1) on the outer ring is firmly outside. The last line is the kernel trick done by hand: one extra feature, x12+x22x_1^2 + x_2^2, 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:

python · try it yourself
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 γ=1\gamma = 1, and the best cell (C=10C = 10, γ=1\gamma = 1) scores 0.944 on the 90 held-out points. The corner C=100C = 100, γ=100\gamma = 100 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 (γ\gamma multiplies squared distances), the scaler belongs in the pipeline.

Cost and scale

A kernel SVM works with the n×nn \times n kernel matrix. Training time grows between n2n^2 and n3n^3, and prediction costs one kernel evaluation per support vector. Up to about 10410^4 to 10510^5 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 nn, need scaling and a CC, γ\gamma 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 1/(d⋅Var⁡(X))1/(d \cdot \operatorname{Var}(X)), 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=True in a hurry. It runs an internal 5-fold cross-validation (slow) and its probabilities can disagree with predict.

Practice

  1. For two points at distance 2, what is the RBF kernel value with γ=0.5\gamma = 0.5 and with γ=5\gamma = 5?
Answer

exp⁡(−0.5⋅4)=e−2≈0.135\exp(-0.5 \cdot 4) = e^{-2} \approx 0.135 and exp⁡(−5⋅4)=e−20≈2×10−9\exp(-5 \cdot 4) = e^{-20} \approx 2 \times 10^{-9}. With the large γ\gamma, the two points are effectively unrelated, which is why large γ\gamma makes each support vector act alone.

  1. Why does the SVM need only the kernel, never ϕ(x)\boldsymbol{\phi}(\mathbf{x}) itself?
Answer

Both the dual objective and the decision function contain the data only through dot products ϕ(xi)⊤ϕ(xj)\boldsymbol{\phi}(\mathbf{x}_i)^\top \boldsymbol{\phi}(\mathbf{x}_j), and the kernel computes exactly these values from the original inputs.

Test yourself

What does increasing γ\gamma in an RBF SVM do?

  1. Widens each support vector's influence, smoother boundary
  2. Narrows each support vector's influence, more complex boundary
  3. Changes the margin penalty
  4. Turns the model linear

Which quantities define a trained kernel SVM's decision function?

  1. A weight per feature only
  2. The support vectors, their coefficients αiyi\alpha_i y_i, the intercept and the kernel
  3. All training points with equal weights
  4. The class means

Training accuracy is 1.0, test accuracy much lower, and nearly every point is a support vector. What should you change?

  1. Increase gamma and C
  2. Decrease gamma and/or C
  3. Remove the scaler
  4. Use more support vectors