Sub topic 11
Reading gamma in the RBF kernel
This chapter assumes you know the kernel trick, the role of C, and basic NumPy. It covers what gamma does in the RBF kernel and how to spot a bad value.
What gamma controls
The RBF kernel measures similarity between two points:
K(x, z) = exp(-gamma * ||x - z||^2)
The value is 1 when the points coincide and falls toward 0 as they move apart. Gamma sets how fast it falls. A large gamma makes similarity vanish at short distances, so each training point influences only its close neighbors. A small gamma makes similarity decay slowly, so each point influences a wide region.
You can read gamma as an inverse length scale. Roughly, 1/gamma sets the squared distance over which two points still count as similar.
import numpy as np
def rbf_kernel_matrix(A, B, gamma):
sq_dists = (A ** 2).sum(axis=1)[:, None] + (B ** 2).sum(axis=1)[None, :] - 2.0 * A @ B.T
return np.exp(-gamma * np.maximum(sq_dists, 0.0))
X = np.array([[0.0, 0.0], [1.0, 0.0], [3.0, 3.0]])
for gamma in [0.05, 0.5, 5.0]:
print("gamma =", gamma)
print(np.round(rbf_kernel_matrix(X, X, gamma), 3))At gamma = 0.05 even the distant third point keeps noticeable similarity to the others. At gamma = 5.0 the matrix is close to the identity: every point is similar only to itself.
Effect on the decision boundary
The fitted decision function is a weighted sum of kernel bumps centered on the support vectors. Gamma sets the width of each bump.
- Small gamma: wide bumps blend together. The boundary is smooth and approaches a nearly linear shape. This risks underfitting (high bias).
- Large gamma: narrow bumps. The boundary wraps tightly around individual points and can form small islands around noise. This risks overfitting (high variance).
At the extreme of very large gamma, almost every training point becomes a support vector, and the model memorizes the training set.
Gamma and C interact
C controls how much margin violation is penalized. Gamma controls how flexible the boundary can be. They are not independent. A large gamma with a large C gives the most overfit model. A small gamma with a small C gives the most underfit one. Good models often sit along a diagonal band of the (C, gamma) grid, so tune the two together.
Common errors
- Reading gamma without scaling. Gamma acts on raw distances. If one feature has a range of thousands, it dominates the distance and gamma means little. Scale first.
- Comparing gamma across datasets. The same number means different things at different feature scales and dimensions.
- Tuning on a linear grid. Useful values span orders of magnitude. Search on a log scale, such as 0.001, 0.01, 0.1, 1, 10.
- Trusting training accuracy. Perfect training accuracy with large gamma is a warning sign, not a success.
Checking it in code
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.25, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
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.named_steps["svc"].n_support_.sum()
print(gamma, "train:", round(model.score(X_train, y_train), 3),
"test:", round(model.score(X_test, y_test), 3), "support vectors:", n_sv)As gamma grows, expect training accuracy to rise, test accuracy to peak and then drop, and the support vector count to approach the training set size (300 here).
Exercise
A model with RBF kernel has 99% training accuracy, 78% test accuracy, and nearly every training point is a support vector. Should you raise or lower gamma, and why?
Show answer
Lower it. These are signs of overfitting from narrow bumps. A smaller gamma widens each point's influence and smooths the boundary. Lowering C can help too.