Sub topic 11
Reading gamma in the RBF kernel
This chapter assumes you know the soft-margin SVM, the role of C, and the kernel trick from the earlier chapters. You should also be comfortable with NumPy and with the idea of overfitting. Here the focus is one parameter: gamma, the width control of the RBF kernel.
What the kernel computes
The RBF (radial basis function) kernel measures similarity between two points:
K(a, b) = exp(-gamma * ||a - b||^2)
Two properties follow directly from the formula:
- When a equals b, the distance is 0 and K is exp(0) = 1. This is the maximum similarity.
- As the distance grows, K decays toward 0. Gamma sets how fast.
The next snippet prints K for a few distances and gammas. It shows the decay without any SVM involved.
import numpy as np
distances = np.array([0.0, 0.5, 1.0, 2.0, 4.0])
for gamma in [0.1, 1.0, 10.0]:
k = np.exp(-gamma * distances ** 2)
print(f"gamma={gamma:>4}:", np.round(k, 4))With gamma = 0.1, a point 4 units away still has similarity of about 0.20. With gamma = 10, a point 1 unit away has similarity of about 0.00005. Large gamma makes the kernel very local. Small gamma makes it broad.
Gamma as an inverse length scale
It helps to rewrite the kernel with a length scale sigma, where gamma = 1 / (2 * sigma^2). Then sigma is the distance at which similarity drops to about exp(-0.5), or 0.61. Small gamma means large sigma: far-apart points still count as similar. Large gamma means small sigma: only very near neighbours count.
Scikit-learn's gamma="scale" default uses 1 / (nfeatures * X.var()). This ties the length scale to the spread of the data. gamma="auto" uses 1 / nfeatures and ignores the variance, so it only suits data that is already standardized.
What gamma does to the decision function
The fitted SVM scores a new point x as a weighted sum of kernels centred on the support vectors:
f(x) = sum over support vectors of (alphai * yi * K(x_i, x)) + b
Each support vector contributes a bump of height set by its dual weight and width set by gamma. The decision boundary is where the summed bumps cross zero.
- Small gamma. Bumps are wide and overlap heavily. The sum is smooth, and the boundary approaches a nearly linear or gently curved shape. The model has high bias and low variance. It can underfit.
- Large gamma. Bumps are narrow. Each support vector controls only a small neighbourhood, so the boundary wraps around individual points and forms islands. The model has low bias and high variance. It overfits.
In the extreme of very large gamma, K between distinct points is almost 0, so the kernel matrix approaches the identity. Every training point is then nearly orthogonal to every other in feature space. The SVM can separate nearly any labelling of the training set, and it does not generalize. Almost every training point becomes a support vector.
The extreme of very small gamma has its own limit. Since exp(-gamma d^2) is approximately 1 - gamma d^2 for small gamma * d^2, the RBF SVM behaves like a linear classifier, provided C is scaled up to compensate.
Observing the effect
This experiment fits the same data at several gamma values and reports training accuracy, test accuracy, and the support vector count.
from sklearn.datasets import make_moons
from sklearn.model_selection import 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=400, noise=0.3, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
print("gamma train test n_support")
for gamma in [0.01, 0.1, 1, 10, 100]:
model = make_pipeline(StandardScaler(), SVC(kernel="rbf", C=1.0, gamma=gamma))
model.fit(X_train, y_train)
n_sv = model[-1].n_support_.sum()
print(f"{gamma:<7} {model.score(X_train, y_train):.3f} "
f"{model.score(X_test, y_test):.3f} {n_sv}")Typical output shows a pattern, though exact numbers vary by library version:
- At gamma = 0.01, both scores are low. The model underfits, and many points are support vectors because the boundary is too stiff to fit them.
- Around gamma = 1, test accuracy peaks.
- At gamma = 100, training accuracy approaches 1.0 while test accuracy falls, and the support vector count climbs toward the training set size.
A growing gap between train and test scores is the signature of too large a gamma. A rising support vector fraction is a second warning sign.
Gamma and C interact
Gamma and C do not act independently. Both control complexity, and good settings lie along a diagonal band in the (C, gamma) grid.
- A large gamma with a small C can still generalize, because small C permits many margin violations and keeps the function smooth.
- A small gamma with a large C can compensate for the stiff kernel by penalizing errors heavily. This approximates a flexible linear model.
- A large gamma with a large C gives the most complex models and the highest overfitting risk.
For this reason, tune the two together, as in the earlier grid search chapter, and search on a logarithmic scale. A common grid is C from 1e-2 to 1e3 and gamma from 1e-4 to 1e1, with factors of 10. Refine around the best cell with a finer grid afterwards.
Gamma depends on feature scale
The squared distance sums over all features. If one feature has a range of thousands and another has a range of 0 to 1, the large feature dominates every distance. Gamma then effectively acts on that one feature, and the others are ignored.
Scaling also changes what a good gamma value means. After standardization, each feature has unit variance, so typical squared distances grow with the number of features. This is why gamma="scale" divides by n_features: it keeps gamma * d^2 at a sensible magnitude as dimensionality changes.
Common mistakes
- Reading gamma values across datasets. A gamma of 0.5 means different things at different feature scales and dimensions. Compare gamma only within one preprocessed dataset.
- Using a linear grid. Values like 0.1, 0.2, 0.3 waste evaluations. The effect of gamma is multiplicative.
- Trusting training accuracy. Large gamma always raises it. Judge by cross-validated score.
- Ignoring support vector count. If most training points are support vectors, prediction is slow and the model is probably too flexible.
- Using
gamma="auto"on unscaled data. It ignores the variance and can produce a kernel that is nearly constant or nearly the identity.
Choosing a starting point
A practical procedure:
- Standardize the features in a pipeline.
- Start with
gamma="scale"and C = 1, and record the cross-validated score. - Run a logarithmic grid over C and gamma centred on those values.
- If the best value sits on the edge of the grid, extend the grid in that direction.
- Check the train and test gap and the support vector fraction at the chosen setting.
Exercise
You fit an RBF SVM and get 100% training accuracy but 70% cross-validated accuracy. About 95% of training points are support vectors. Which direction should you move gamma, and what else could you change?
Show answer
Decrease gamma. The signs point to a kernel that is too local: perfect training accuracy, a large generalization gap, and almost every point acting as a support vector. A smaller gamma widens the bumps and smooths the boundary. You can also lower C to allow more margin violations, and you should confirm the features are standardized. Then re-run the cross-validated grid search on a logarithmic scale.
Exercise
With gamma = 2, what is the RBF similarity between two points at distance 0.5? What is it at distance 3?
Show answer
At distance 0.5: exp(-2 0.25) = exp(-0.5), about 0.607. At distance 3: exp(-2 9) = exp(-18), about 1.5e-8, which is effectively zero. The second point has no influence on the first.