Support Vector Machines and Margins
Several lines may separate the same labelled examples. We need a reason to prefer one, and a way to handle examples that cannot all be separated cleanly.
14 sections · 4 questions · 2 coding challenges
The arrow keys move between sections too.
Separating Examples That Do Not Cooperate
BOTIE
Cortes and Vapnik's 1995 support-vector networks paper allowed the classifier to handle data that could not be separated perfectly. A point could violate the margin, but doing so carried a cost. The model could then balance a wider margin against those violations. We will use small geometric examples to understand that choice; the paper's experiments concerned optical character recognition.
Sources for this history
Which Separating Line Leaves Us Room to Be Wrong?
Imagine two groups of inspected parts plotted by their measurements. We can draw a line between the groups, but we can also slide or rotate that line and still classify every training part correctly. Which line should we choose?
Measurements are not perfectly stable. A boundary pressed against one part leaves little room for a slightly different reading. Let's look for space between the boundary and the nearby examples, then decide what to do when a few observations intrude into that space.
The labelled measurements and proposed boundary are supplied for inspection, not fitted here.
Step 1 of 4
Many lines separate these groups
The left points have label -1 and the right points label +1. A vertical boundary anywhere in the gap separates this sample.
Vertical: Vertical position
Horizontal: Horizontal position
Step 2 of 4
Move the boundary away from the nearest points
The centred boundary leaves equal room on both sides. The nearest observations limit how wide that empty strip can become.
Vertical: Vertical position
Horizontal: Horizontal position
Step 3 of 4
Allow a cost when observations enter the margin
Correct classification alone is not enough for zero hinge loss. An example also needs a sufficiently large signed score.
| Example | Signed scores | Hinge losses |
|---|---|---|
| Example 1 | 1.5 | 0 |
| Example 2 | 0.5 | 0.5 |
| Example 3 | -0.5 | 1.5 |
Example 1
- Signed scores
- 1.5
- Hinge losses
- 0
Example 2
- Signed scores
- 0.5
- Hinge losses
- 0.5
Example 3
- Signed scores
- -0.5
- Hinge losses
- 1.5
Step 4 of 4
Two correct predictions can satisfy the margin differently
Both of these labelled points are on the correct side. One is still close to the boundary, so it contributes hinge loss; the other lies beyond the requested margin. Correct classification alone does not capture that distinction.
| Observation | Label multiplied by score | Hinge loss | Margin satisfied? |
|---|---|---|---|
| Near the boundary | 0.25 | 0.75 | No |
| Farther from the boundary | 1.5 | 0 | Yes |
Near the boundary
- Label multiplied by score
- 0.25
- Hinge loss
- 0.75
- Margin satisfied?
- No
Farther from the boundary
- Label multiplied by score
- 1.5
- Hinge loss
- 0
- Margin satisfied?
- Yes
A margin asks for separation beyond a correct sign
The label turns either correct side into a positive signed score. The remaining shortfall measures margin violation, and the mean summarises the proposed boundary's examples.
Which labelled parts sit too close to the boundary?
A point can be on the correct side and still lie inside the requested margin. Change a score or label and inspect the shortfall before averaging over the parts.
BOTIE
Mean hinge loss for the proposed boundary
0.25
Follow the operations
1. Set a constant
1
2. Known labels: -1 or +1
- 0-1
- 1-1
- 21
- 31
3. Part measurements by row
-2 -1 1 2 4. Boundary weights
- 00.5
5. Matrix times vector
- 0-1
- 1-0.5
- 20.5
- 31
6. Boundary bias
0
7. Add
- 0-1
- 1-0.5
- 20.5
- 31
8. Multiply
- 01
- 10.5
- 20.5
- 31
9. Subtract
- 00
- 10.5
- 20.5
- 30
10. Keep positive values
- 00
- 10.5
- 20.5
- 30
11. Mean
0.25
12. Result
0.25
The weights are supplied, not fitted. A full SVM objective also penalises their norm, and its score is not a calibrated probability.
1. Give the Boundary a Score
A linear score multiplies each measurement by a weight and adds a bias. The zero-score locations form the boundary. For this binary model, use class labels minus one and plus one. The score's sign chooses the side.
Multiplying the score by the known label makes a positive value mean correct-side placement for either class. This product is the functional margin.
score = w · x + b
signed score = y × score
For y = -1 and score = -0.5:
signed score = (-1) × (-0.5) = 0.5A positive signed score is on the correct side. Its numerical size still depends on how the weights and bias are scaled.
2. Separate Score Size From Geometric Distance
Doubling every weight and the bias preserves the zero boundary while doubling all scores. It has not moved any observation. Dividing by the weight vector's length removes that arbitrary scale and gives signed perpendicular distance.
The conventional margin boundaries have scores minus one and plus one. Once we use that convention, a smaller weight norm means a wider strip.
signed distance = y(w · x + b) / ||w||
width between score -1 and score +1 = 2 / ||w||The distances depend on the feature units. Fit a scaler using training data before comparing features with incompatible scales.
3. Charge for Violating the Margin
An observation with signed score at least one lies on or beyond its margin boundary and receives zero hinge loss. A correctly classified observation inside the strip still receives a positive loss. A wrong-side observation receives a still larger loss.
Hinge loss measures this shortfall. It does not represent the probability of a class.
hinge = max(0, 1 - signed score)
signed score 1.5 → loss 0
signed score 0.5 → loss 0.5
signed score -0.5 → loss 1.5The workshop calculates these violations for supplied weights. It lets you inspect an objective component without pretending the weights were learned there.
4. Balance a Wider Margin Against Violations
The soft-margin objective combines a weight penalty with hinge losses. In the sum convention below, a larger C makes violations more expensive relative to widening the margin. Some formulations average losses and rescale the regularisation parameter; compare conventions before copying settings.
An optimiser chooses weights and bias to reduce the combined objective. Examples on or inside the margin can matter to the solution. The examples with nonzero dual coefficients are the support vectors.
Objective = (1/2)||w||² + C × Σ hinge_i
If ||w||² = 0.25, C = 0.5, and Σ hinge_i = 1:
objective = 0.125 + 0.5 = 0.625This objective tolerates overlap. It does not promise that a linear boundary can express every useful pattern.
5. Connect the Boundary to Richer Representations
If a straight boundary is unsuitable in the measured coordinates, transformed features may help. Kernel support-vector machines express comparisons through kernel evaluations. The kernel lesson explains how such comparisons can correspond to a more useful representation.
Choose the penalty, kernel, and scaling through validation. A classifier's raw decision score is not automatically a calibrated probability, and increasing flexibility can fit accidental patterns.
We now have a reason to choose a boundary, an explicit cost for exceptions, and a connection to the kernel machinery already in the course.
6. Which Observations Push the Boundary?
A point outside its margin already satisfies the hinge requirement, so that loss contributes no gradient there. A point inside the margin, including a correctly classified one, pushes the boundary toward a larger signed score. The weight penalty simultaneously pulls the weights toward zero.
The bias is not penalised in the convention used here. We average hinge losses and multiply them by C. This differs by a dataset-size factor from a sum-loss convention, so a copied numerical C need not represent the same tradeoff.
7. Repeat the Update Until the Boundary Can Be Checked
Begin with zero weights, calculate every signed score, collect only margin violations and make a small subgradient step. Repeat that procedure, then examine classifications and margin values separately.
Hinge loss is not differentiable exactly at its corner. The code uses zero contribution when the margin is exactly one, an allowed subgradient choice. A fixed step size can oscillate near the optimum; this small demonstration is not a replacement for a production solver.
Train a one-feature separating rule
Negative and positive measurements belong to different inspected classes.
import numpy as np
x = np.array([-2., -1., 1., 2.])
y = np.array([-1., -1., 1., 1.])
w, b, C = 0., 0., 2.
for step in range(1000):
active = y*(w*x+b) < 1
dw = w - C*np.mean(np.where(active, y*x, 0.))
db = -C*np.mean(np.where(active, y, 0.))
rate = 0.1 / np.sqrt(step+1)
w -= rate*dw
b -= rate*db
print(np.sign(w*x+b).astype(int).tolist())
print(bool(w > 0), bool(abs(b) < 1e-10))[-1, -1, 1, 1]
True TrueThe symmetric data produce a boundary at zero. Correct labels alone do not establish that the margin objective is fully optimised.
8. A Wide Margin Still Depends on the Ruler
Changing a feature from metres to millimetres changes its coefficient scale and the geometry of the weight penalty. Standardise using training statistics when that matches the feature meaning, and use the same transform for validation and prediction.
Inspect sensitivity to C on held-out records rather than choosing the setting with the widest-looking training strip. Overlapping classes, measurement errors and nonlinear relationships can all make a perfect separating line an unsuitable target.
Check yourself
Questions on Parts 1 to 8
Question 1 of 4
Which pair contains the hinge losses?
Use the information below.
Labels: [-1, 1]
Decision scores: [-0.5, -0.5]
Hinge loss: max(0, 1 - label × score)Try it with Botie
Build with Botie
Write and run Python