Sub topic 5
Controlling the trade-off with C
This chapter assumes you know the soft-margin objective from the previous chapter: the margin term, the slack variables, and a linear decision function w·x + b. You should also be comfortable with scikit-learn's fit and score, and with the idea of overfitting.
What C does in the objective
The soft-margin SVM minimizes
0.5 · ||w||² + C · Σ ξᵢ
subject to yᵢ(w·xᵢ + b) ≥ 1 − ξᵢ and ξᵢ ≥ 0, with labels yᵢ in {−1, +1}.
The first term rewards a wide margin, because the margin width is 2 / ||w||. The second term charges for every unit of slack ξᵢ. C is the price per unit of slack, and it sets how the two terms are weighed against each other.
Each ξᵢ has a concrete meaning:
| Slack value | Where the point sits |
|---|---|
| ξ = 0 | Correct side, on or outside the margin |
| 0 < ξ ≤ 1 | Correct side, but inside the margin |
| ξ > 1 | On the wrong side of the hyperplane (misclassified) |
C is a regularization strength in the inverse direction. A small C means strong regularization, and a large C means weak regularization.
The two extremes
With a very small C, slack is cheap. The optimizer prefers a small ||w||, so it gets a wide margin and tolerates many violations. The model is simple and can underfit (high bias).
With a very large C, slack is expensive. The optimizer shrinks the margin to fit as many training points as it can. The boundary bends toward individual noisy points, and the model can overfit (high variance).
As C grows toward infinity on linearly separable data, the solution approaches the hard-margin SVM. On non-separable data, a huge C does not make the problem infeasible, because slack is still allowed. It only makes slack very costly, and the solver may need many more iterations.
Observing the trade-off
The script below fits a linear SVM on overlapping clusters for a range of C values. For each fit it reports the margin width, the number of support vectors, and train and test accuracy.
import numpy as np
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.0, random_state=1)
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, 1000]:
clf = SVC(kernel="linear", C=C).fit(X_train, y_train)
width = 2.0 / np.linalg.norm(clf.coef_)
n_sv = clf.n_support_.sum()
train_acc = clf.score(X_train, y_train)
test_acc = clf.score(X_test, y_test)
print(f"C={C:<7} width={width:7.3f} SVs={n_sv:3d} "
f"train={train_acc:.3f} test={test_acc:.3f}")When you run it, expect these trends:
- The margin width shrinks as C grows.
- The support-vector count falls, because fewer points sit inside or on the wrong side of the margin.
- Training accuracy rises or stays flat.
- Test accuracy often peaks at a middle value of C and may drop or plateau at the extremes.
The exact numbers depend on the data and the split. On a very small C, the model may predict poorly because ||w|| is pushed so low that the boundary hardly responds to the data.
Reading slack from a fitted model
You can recover the slack values from decision_function. For a linear kernel, decision_function(x) equals w·x + b, so ξᵢ = max(0, 1 − yᵢ · f(xᵢ)).
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.svm import SVC
X, y = make_blobs(n_samples=200, centers=2, cluster_std=2.0, random_state=1)
y_pm = 2 * y - 1 # convert {0, 1} labels to {-1, +1}
for C in [0.01, 1, 100]:
clf = SVC(kernel="linear", C=C).fit(X, y)
slack = np.maximum(0.0, 1.0 - y_pm * clf.decision_function(X))
inside_margin = np.sum(slack > 1e-6)
misclassified = np.sum(slack > 1.0)
max_alpha = np.abs(clf.dual_coef_).max()
print(f"C={C:<5} total slack={slack.sum():8.2f} "
f"violations={inside_margin:3d} misclassified={misclassified:3d} "
f"max |dual coef|={max_alpha:.3f}")Two things to notice. Total slack falls as C grows, which matches the objective. The largest absolute dual coefficient never exceeds C. That bound comes from the dual formulation, which a later chapter derives. For now, treat it as a useful fact: support vectors with ξ > 0 are the ones whose dual coefficient hits the cap C.
Practical points and edge cases
C multiplies a sum, not a mean. In the objective, the loss term is the total over all training points. If you double the dataset with similar data, the loss term roughly doubles while the margin term stays the same. A C that worked on 1,000 samples is therefore effectively less regularizing on 100,000. Re-tune C when the amount of data changes a lot.
Search C on a log scale. The effect of C is roughly multiplicative, so useful grids look like 0.01, 0.1, 1, 10, 100. Linear spacing such as 1, 2, 3, 4 wastes most of the search.
Feature scale changes the meaning of C. If features are multiplied by a constant, ||w|| changes inversely, and the best C changes with it. With an RBF kernel, scale also affects the distances inside the kernel. Standardize features first, inside a pipeline, as a later chapter covers.
Imbalanced classes. The class_weight option in SVC multiplies C per class. Setting class_weight={1: 5} makes slack on class 1 five times as expensive, which pushes the boundary away from that class. Use it when mistakes on one class cost more.
SVC and LinearSVC are not the same objective. LinearSVC defaults to squared hinge loss and also penalizes the intercept. For the same C, the two can give different boundaries. Compare them with care.
C interacts with other hyperparameters. With an RBF kernel, C and gamma must be tuned together. A large gamma with a large C is the classic overfitting setup. Do not choose C alone and then gamma, because the best values depend on each other.
A cheap diagnostic. If training accuracy is low at every C you try, the model is underfitting for reasons C cannot fix, and a more flexible kernel is the better lever. If training accuracy is near 100% and test accuracy is much lower, reduce C or, with an RBF kernel, reduce gamma.
Exercises
Exercise
You fit a linear SVM with C = 0.001 and get low training accuracy and low test accuracy. Which direction should you move C, and which quantity in the objective explains why?
Show answer
Increase C. A tiny C makes slack almost free, so the 0.5·||w||² term dominates and the model keeps ||w|| small and the margin very wide, even if many points are misclassified. Raising C makes the C·Σξᵢ term matter more, so the optimizer works harder to reduce violations.
Exercise
A point has yᵢ(w·xᵢ + b) = 0.4 at the optimum. What is its slack ξᵢ, and is it classified correctly?
Show answer
ξᵢ = max(0, 1 − 0.4) = 0.6. Since 0 < ξᵢ ≤ 1, the point is on the correct side of the hyperplane but inside the margin, so it is classified correctly and is a margin violation.
Exercise
You trained on 2,000 samples with C = 1 and now train on 200,000 similar samples. Why might the same C regularize less, and what should you do?
Show answer
The loss term is a sum over samples, so it grows with the data while the margin term 0.5·||w||² does not. The same C therefore puts relatively more weight on fitting the data. Re-tune C by cross-validation on the larger set, usually trying smaller values.