Sub topic 4
Soft margins and slack variables
This chapter assumes you know the hard-margin SVM from the previous chapter: the primal problem, the margin 2/‖w‖, and the constraint yi(w·xi + b) ≥ 1. It also assumes basic constrained optimization and NumPy. Labels here are in {-1, +1}.
Why the hard margin breaks
The hard-margin problem is:
minimize ½‖w‖² subject to yi(w·xi + b) ≥ 1 for every i.
This has a solution only if the classes are linearly separable. Two failure modes appear in real data:
- No feasible solution. If one point from class +1 sits inside a cloud of class -1 points, no hyperplane satisfies every constraint. The optimizer has nothing to return.
- A fragile solution. Even when the data are separable, one outlier near the boundary can force a very narrow margin. The boundary then depends heavily on that single point, which is a form of overfitting.
The soft-margin SVM fixes both by allowing some points to violate the margin, at a price.
Slack variables
Each training point gets a slack variable ξ_i ≥ 0 that measures how far it violates the margin constraint. The constraint becomes:
yi(w·xi + b) ≥ 1 − ξi, with ξi ≥ 0.
The soft-margin primal problem is:
minimize ½‖w‖² + C Σ ξi subject to yi(w·xi + b) ≥ 1 − ξi and ξ_i ≥ 0.
The first term rewards a wide margin. The second term penalizes total violation. Because the constraints are always satisfiable (take ξ_i large enough), a solution always exists. The problem is still a convex quadratic program, so there is one global optimum.
What the value of ξ_i means
The value of ξ_i places point i in one of three zones.
| Value of ξ_i | Position of the point | Meaning |
|---|---|---|
| ξ_i = 0 | On or beyond the margin, correct side | No violation |
| 0 < ξ_i ≤ 1 | Inside the margin, but still on the correct side | Margin violation, correctly classified |
| ξ_i > 1 | On the wrong side of the hyperplane | Misclassified |
The boundary at ξi = 1 comes from the decision rule. A point on the hyperplane has y(w·x + b) = 0, so 1 − ξ = 0 gives ξ = 1. Anything with ξ > 1 has a negative margin value, so it is misclassified. This also means Σ ξi is an upper bound on the number of training errors.
Computing slack directly
At the optimum, each slack variable takes the smallest value the constraint allows:
ξi = max(0, 1 − yi(w·x_i + b))
This is the hinge loss, covered in a later chapter. The function below computes the slack values and the soft-margin objective for given parameters.
import numpy as np
def slacks(w, b, X, y):
# y must contain labels in {-1, +1}
margins = y * (X @ w + b)
return np.maximum(0.0, 1.0 - margins)
def soft_margin_objective(w, b, X, y, C):
xi = slacks(w, b, X, y)
return 0.5 * np.dot(w, w) + C * xi.sum()
X = np.array([[2.0, 2.0], [3.0, 3.0], [0.2, 0.2], [-1.0, -1.0], [-2.0, -2.0]])
y = np.array([1, 1, 1, -1, -1])
w = np.array([0.5, 0.5])
b = 0.0
print("slack:", slacks(w, b, X, y))
print("objective, C=1:", soft_margin_objective(w, b, X, y, 1.0))With these values the point (0.2, 0.2) has y(w·x + b) = 0.2, so its slack is 0.8. It is inside the margin but still correctly classified. The point (-1, -1) has margin value exactly 1, so its slack is 0. The point (2, 2) has margin value 2, so its slack is also 0.
The role of C
C sets the exchange rate between a wide margin and few violations.
- Large C. Violations are expensive. The optimizer shrinks the margin to fit the training points, which lowers bias and raises variance. As C → ∞ the soft margin approaches the hard margin.
- Small C. Violations are cheap. The optimizer accepts a wide margin with many violations, which raises bias and lowers variance.
A common misreading is that C is a "margin width" setting. It is a penalty weight. The margin width follows from the optimization, and it changes as C changes.
In scikit-learn, C applies per sample and the regularization strength is proportional to 1/C. The default is C=1.0. The following code shows how the number of support vectors and the margin change with C on overlapping data.
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.5, random_state=3)
for C in [0.01, 0.1, 1, 10, 1000]:
clf = SVC(kernel="linear", C=C).fit(X, y)
margin_width = 2.0 / np.linalg.norm(clf.coef_)
print(f"C={C:>7}: support vectors={clf.n_support_.sum():3d}, "
f"margin width={margin_width:.3f}, "
f"train accuracy={clf.score(X, y):.3f}")You should see the margin width fall and the support vector count drop as C grows. Training accuracy typically rises slightly, then flattens. Exact numbers depend on the library version.
Reading the fitted model
After fitting, you can recover the slack values and check them against the three zones. The decision function returns w·x + b, so multiplying by the label in {-1, +1} gives the margin value.
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.svm import SVC
X, y01 = make_blobs(n_samples=100, centers=2, cluster_std=2.0, random_state=1)
y = 2 * y01 - 1
clf = SVC(kernel="linear", C=1.0).fit(X, y)
m = y * clf.decision_function(X)
xi = np.maximum(0.0, 1.0 - m)
print("zero slack: ", int((xi < 1e-6).sum()))
print("inside margin: ", int(((xi >= 1e-6) & (xi <= 1)).sum()))
print("misclassified (>1): ", int((xi > 1).sum()))
print("sum of slack: ", round(xi.sum(), 3))Points with positive slack are always support vectors. Points with exactly zero slack can also be support vectors if they lie on the margin. This is the connection to the next chapters.
Common errors
- Using labels in {0, 1} in your own formulas. The expression y(w·x + b) needs labels in {-1, +1}. scikit-learn accepts any labels, but a hand-written hinge loss does not.
- Treating slack as a per-point hyperparameter. The ξ_i are optimization variables, solved for during training. Only C is chosen by you.
- Expecting a bigger C to always improve results. A large C fits noise and lowers test accuracy on noisy data. Choose C by cross-validation, which a later chapter covers.
- Ignoring feature scale. The penalty C Σ ξ_i is measured in units of the margin, which depends on the scale of the features. Unscaled features make C hard to interpret.
- Comparing C values across implementations. Different libraries scale the objective differently, for example by averaging the loss over samples. A C that works in one may not carry over to another.
Summary of the formulation
| Piece | Hard margin | Soft margin |
|---|---|---|
| Constraint | y_i(w·x_i + b) ≥ 1 | y_i(w·x_i + b) ≥ 1 − ξ_i, ξ_i ≥ 0 |
| Objective | ½‖w‖² | ½‖w‖² + C Σ ξ_i |
| Feasible on overlapping data | No | Yes |
| Sensitive to outliers | Very | Controlled by C |
| Free parameters | None | C |
Exercise
A trained linear SVM gives w = (1, 1) and b = -1. A point x = (0.5, 0.25) has label y = +1. Compute its slack ξ and say which zone it is in: outside the margin, inside the margin on the correct side, or misclassified.
Show answer
w·x + b = 0.5 + 0.25 − 1 = −0.25. The margin value is y(w·x + b) = −0.25. So ξ = max(0, 1 − (−0.25)) = 1.25. Because ξ > 1, the point is on the wrong side of the hyperplane and is misclassified.
Exercise
You fit a linear SVM on noisy, overlapping data and see 95% training accuracy but only 80% accuracy in cross-validation. Should you raise or lower C, and why?
Show answer
Lower C. The gap between training and validation accuracy suggests overfitting. A smaller C makes violations cheaper, which widens the margin and reduces variance. Confirm the choice with a cross-validated search over C, with scaling inside a pipeline.