Sub topic 13
Tuning C and gamma with grid search
This chapter assumes you know how the soft-margin SVM uses C, how the RBF kernel uses gamma, and why features need scaling. It also assumes you know k-fold cross-validation and have used scikit-learn pipelines. Here you will search for good values of C and gamma, and you will learn to read the results.
Why these two parameters need a search
An RBF SVM has two main hyperparameters, and they interact.
- C sets the price of margin violations. A small C allows a wide margin with many violations, so the model has high bias and low variance. A large C punishes violations, so the model fits the training data closely.
- gamma sets how far one training point's influence reaches in the kernel
exp(-gamma * ||x - x'||^2). A small gamma gives smooth, nearly linear boundaries. A large gamma gives tight bumps around individual points.
Neither value can be derived from the data in closed form. You choose them by trying candidates and measuring held-out performance. Because the two interact, you search them jointly. A large gamma with a small C can behave like a moderate gamma with a moderate C, and tuning one at a time misses this.
| Setting | Boundary | Typical failure |
|---|---|---|
| Small C, small gamma | Very smooth, close to linear | Underfitting |
| Large C, large gamma | Wiggly, hugs single points | Overfitting |
| Small C, large gamma | Local bumps, but heavily regularized | Mostly predicts one class |
| Large C, small gamma | Smooth but strict on violations | Often fine, can be slow to train |
The basic search
Grid search tries every combination in a grid and scores each with cross-validation. The scaler goes inside the pipeline, so each fold fits it only on that fold's training part. Scaling before the search would leak validation statistics into training.
from sklearn.datasets import make_moons
from sklearn.model_selection import GridSearchCV, 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)
pipe = make_pipeline(StandardScaler(), SVC(kernel="rbf"))
param_grid = {
"svc__C": [0.1, 1, 10, 100],
"svc__gamma": [0.01, 0.1, 1, 10],
}
grid = GridSearchCV(pipe, param_grid, cv=5)
grid.fit(X_train, y_train)
print(grid.best_params_)
print("test accuracy:", grid.score(X_test, y_test))Parameter names use the pipeline step name, a double underscore, then the parameter. The step made by make_pipeline is named svc, so the keys are svc__C and svc__gamma. A wrong prefix raises an error that lists the valid parameter names.
With 4 values of C, 4 of gamma, and 5 folds, the search fits 80 models. After it finishes, GridSearchCV refits the best combination on the whole training set (refit=True by default). grid.score and grid.predict then use that refitted model.
The test set is touched once, after the search. If you tune on the test set, the reported accuracy is optimistic.
Choosing the grid
Both parameters act multiplicatively, so a useful grid is logarithmic. The gap between C=1 and C=10 matters as much as the gap between C=10 and C=100. A linear grid such as 1, 2, 3, 4 wastes most of its points.
A common starting range is C from 1e-2 to 1e3 and gamma from 1e-3 to 1e2, with one point per power of ten. Here is that search with a few lines that inspect the results:
import numpy as np
from sklearn.datasets import make_moons
from sklearn.model_selection import GridSearchCV, 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)
pipe = make_pipeline(StandardScaler(), SVC(kernel="rbf"))
param_grid = {
"svc__C": np.logspace(-2, 3, 6),
"svc__gamma": np.logspace(-3, 2, 6),
}
grid = GridSearchCV(pipe, param_grid, cv=5, n_jobs=-1)
grid.fit(X_train, y_train)
res = grid.cv_results_
for i in np.argsort(res["rank_test_score"])[:3]:
print(res["params"][i],
"mean:", round(res["mean_test_score"][i], 3),
"std:", round(res["std_test_score"][i], 3))Look at the top few rows, not only the winner. If the top five combinations score within one standard deviation of each other, the data cannot tell them apart. In that case prefer the simpler model: smaller C and smaller gamma.
The scikit-learn default gamma="scale" equals 1 / (n_features * X.var()). After StandardScaler the variance is about 1, so the default is roughly 1 / n_features. Include values near that default in your grid, because it is a reasonable center for the search.
Refining the search
A coarse grid finds the region, and a finer grid then looks inside it. Take the best pair from the coarse search. Build a second grid that spans about one decade on each side, using factors like 2 or 3, such as best * [0.1, 0.3, 1, 3, 10]. This costs far less than one very fine grid over the whole range.
Check the edges. If the best value sits on the boundary of the grid, for example C=1000 as the largest value tried, the optimum may lie outside. Extend the grid in that direction and search again.
For wide ranges or more parameters, RandomizedSearchCV samples combinations instead of trying all of them. Give it log-uniform distributions such as scipy.stats.loguniform(1e-2, 1e3). A fixed budget of 30 to 60 random draws often matches a full grid.
Pitfalls
- Large C and large gamma are slow. Training time grows sharply when the model has to chase every point, so the corner of the grid with both values large can dominate runtime. Setting
n_jobs=-1runs the folds in parallel. - Accuracy may be the wrong metric. With imbalanced classes, pass
scoring="f1","roc_auc", or"balanced_accuracy". You can also setclass_weight="balanced"on theSVC. - Nested cross-validation for honest estimates.
best_score_is the maximum over many noisy scores, so it is biased upward. To estimate how the whole tuning procedure will perform, wrap the search in an outercross_val_score. On small datasets, this is worth the extra cost. - Fixed seeds and splits. Compare candidates on the same folds.
GridSearchCVdoes this by default, since every candidate sees the same splits.
Exercises
Exercise
A grid search over svc__C in [0.1, 1, 10, 100] returns C=100 as best, with the top three scores 0.912, 0.911, 0.890 for C=100, 10, and 1. What should you do next, and why?
Show answer
Because the best value sits at the edge of the grid, extend the grid upward (for example 1000 and 10000) and rerun the search to see whether the score keeps improving. The scores for C=100 and C=10 are almost equal, so check their standard deviations. If they overlap, prefer C=10, which is the simpler and faster model.
Exercise
Why does the pipeline keys use svc__gamma and not just gamma, and what goes wrong if you scale X before the search?
Show answer
GridSearchCV receives the whole pipeline, so it must route each parameter to a step. The svc__ prefix names the step and the double underscore separates it from the parameter. Scaling before the search lets validation rows influence the scaler's mean and variance, which leaks information and inflates the cross-validation scores.