Sub topic 5
Controlling the Trade-off with C
This chapter assumes you know the soft-margin SVM objective, slack variables, and basic overfitting and cross-validation. Here we focus on what the parameter C does and how to set it.
What C does
The soft-margin objective has two terms:
minimize 0.5·||w||² + C · Σ ξᵢ
The first term rewards a wide margin. The second penalizes the total slack ξᵢ, which measures how far points fall on the wrong side of their margin. C sets the price of slack.
- Large C: slack is expensive. The model fits training points tightly, and the margin narrows. This risks overfitting.
- Small C: slack is cheap. The model tolerates violations, and the margin widens. This risks underfitting.
C is an inverse regularization strength. Small C means strong regularization.
Seeing the effect
The code below fits a linear SVM on overlapping clusters with several values of C. It prints the number of support vectors and the training and test accuracy.
from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
X, y = make_blobs(n_samples=300, centers=2, cluster_std=2.5, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
for C in [0.001, 0.01, 0.1, 1, 10, 100]:
clf = SVC(kernel="linear", C=C).fit(X_train, y_train)
print(
f"C={C:<7} support vectors={clf.n_support_.sum():3d} "
f"train={clf.score(X_train, y_train):.3f} "
f"test={clf.score(X_test, y_test):.3f}"
)As C grows, the number of support vectors usually falls, because fewer points sit inside or beyond the margin. Training accuracy tends to rise. Test accuracy typically peaks at a moderate C and may drop or stay flat after that.
Common errors
- Tuning C on the test set. Choose C by cross-validation on the training data and touch the test set once.
- Searching a narrow linear range. C acts on a multiplicative scale, so search powers of ten, such as 0.01 to 1000.
- Forgetting to scale features. The margin is measured in feature units, so unscaled features distort what a given C means.
- Tuning C alone with an RBF kernel. C interacts with gamma. A large gamma with a large C overfits badly, so tune them together.
- Assuming a large C always helps on separable data. With noisy labels, a large C forces the boundary to chase noise.
Practical guidance
Plot cross-validated score against log C. A good value sits where the score plateaus or peaks. If the score keeps rising at the largest C you tried, extend the grid. If training and validation scores are both low, C is probably too small.
Exercise
A linear SVM scores 0.99 on training data and 0.80 on validation data with C=1000. Which direction should you move C, and why?
Show answer
Lower it. The large gap between training and validation scores indicates overfitting. A smaller C makes slack cheaper, widens the margin, and strengthens regularization. Pick the new value by cross-validation, for example from 0.01 to 100.