Support Vector Machines
The decision boundary that does not just separate the data but separates it with the most breathing room possible. Maximum-margin geometry, the primal/dual quadratic programs and KKT, support vectors and sparsity, the kernel trick, the soft margin with slack and C, and the hinge-loss view that ties SVMs into the regularized-loss family.
01 · Motivation
Why does this matter?
In Chapter 03 we learned that any line putting the positives on one side and the negatives on the other is a valid linear classifier. The perceptron stops the moment it finds any such line. But “any” is not “good”. Between two clouds of points there are infinitely many separating lines, and most of them are nervous — a single new test point could fall on the wrong side because the boundary skimmed too close to existing data.
Support Vector Machines fix this by asking a sharper question: among all the separating hyperplanes, which one leaves the most breathing room? The answer turns out to be unique, computable from a single convex optimization problem, and — through the kernel trick — capable of drawing decision boundaries of essentially arbitrary shape without losing convexity. Three reasons SVMs occupy the place they do:
Robust by construction
The widest possible margin keeps the classifier as far as possible from every training point. Small measurement noise on a new sample cannot easily flip its prediction — the boundary has already moved out of the way.
A sparse, interpretable model
The trained model depends only on a handful of training points — the support vectors. Throw the rest away and the predictions are identical. Few other methods answer “which examples actually mattered?” so cleanly.
Non-linear without local minima
With kernels, the same algorithm learns curved boundaries — even infinite-dimensional ones — by changing one line of code. And the optimization stays a convex QP: one global minimum, no random seeds.
The deeper reason SVMs work
The PAC bounds in Chapter 05 told us that to generalise well we want a hypothesis class with limited capacity. Vapnik’s insight: large-margin classifiers form a smaller effective hypothesis class than arbitrary separators — even if the underlying feature space is huge. Margin is a regulariser, and SVMs are the algorithm that turns this idea into a one-shot quadratic program.
This chapter sits at the confluence of every previous one. From Ch. 03 we keep the linear classifier; from Ch. 05 the VC-dimension argument that motivates large margins; from Ch. 06 we keep kernels — which here are not an afterthought but the engine. Think of the result as kernel ridge classification with a different loss: same mathematical family, sharper geometric story.
02 · Intuition
The idea in plain language
Imagine two clusters of points on a 2-D plot — blue on the left, orange on the right, well separated. Your job is to draw a single straight line that splits them. There are many ways to do it. How do you pick?
The picture below shows two ideas at once. The solid line is the decision boundary. The two dashed lines parallel to it are the margins — the boundary’s safety zones. The width of the corridor between the dashed lines is the margin width; SVMs pick the corridor that is as wide as possible while still being empty in the middle. The points touching the margin are the support vectors: pull any other point inward and the corridor does not move; pull a support vector and the corridor moves with it. They “hold the corridor in place”, and they are the only training points that survive in the final model.
Mantra
Widest possible street, with the smallest number of points touching its edges. Everything in this chapter is some rephrasing or generalisation of that one sentence — including the dual formulation, the kernel trick, and even the soft-margin variant.
Why is a wider margin better?
Two arguments — one geometric, one statistical — both pointing the same way:
- Robustness. If a future point is a slightly noisy version of a training point, it lands in a small ball around the original. The wider the corridor, the more likely that ball stays entirely on the correct side.
- Capacity control. Among all hyperplanes, those achieving a margin of at least on data bounded in a sphere of radius form a hypothesis class with VC-dimension bounded by . Bigger margin smaller effective class better generalisation (Ch. 05).
From perceptron to kernel — the rewrite that opens the door
Recall the perceptron from Ch. 03: . During training, every weight ends up a sum of contributions from the training points it has seen: , where counts how many times point was used. Plug this into the prediction and swap the order of summation:
The sum over features has become a sum over training points. The model now talks about similarities between examples, not about feature weights.
Two huge things just happened. First, the inner product is the only place the features appear — replace it with any valid kernel and the algorithm keeps working, even if lives in an infinite-dimensional space (Ch. 06). Second, if most , the prediction depends only on a sparse subset of the training data — exactly the support-vector picture. SVMs are what you get when you combine this rewrite with the maximum-margin criterion.
An SVM has three pieces, and that is it
- A subset of training points — the support vectors.
- A weight for each of them.
- A kernel that measures similarity.
The prediction is just a weighted vote of how similar the query is to each support vector. It is instance-based learning at heart — only the choice of which instances matter is found by optimisation instead of being memorised wholesale.
03 · Formalism
Definitions and equations
Let the training set be with binary labels — note: not like in logistic regression. This convention lets us multiply labels into expressions and simplify nicely.
The decision function
We use a linear model in some (possibly transformed) feature space, exactly like Ch. 03:
The decision boundary is , a hyperplane in feature space. The vector is its normal; is the offset that shifts it away from the origin.
The functional and geometric margin
Two related notions, and the distinction trips students up every single year:
- Functional margin
- . Positive when classification is correct; rescales with .
- Geometric margin
- . The signed Euclidean distance from to the hyperplane — invariant to rescaling .
The geometric margin of the whole dataset is the smallest such distance:
The maximum-margin hyperplane maximises this . Written directly it is messy:
Outer max over the parameters, inner min over the data. The converts the functional margin into a Euclidean distance.
The rescaling trick → the clean primal
and for any define the same hyperplane, so we are free to choose the scale. Rescale so that the closest training point has functional margin exactly 1: . Then , and maximising the margin is the same as minimising . This is the SVM primal in its standard form:
The factor ½ is cosmetic — it cancels under differentiation. The objective is convex (a paraboloid), the constraints linear, the feasible region a convex polytope. So this is a convex quadratic program with a unique global minimum, provided the data are linearly separable.
A 60-second primer on constrained optimization
The primal is constrained and we want something we can differentiate. The standard tool is the Lagrangian. Two facts to carry into the rest of the chapter:
Constrained optimization in one paragraph
To minimise subject to inequality constraints , build the Lagrangian with multipliers . At the optimum, the KKT conditions hold: stationarity (), primal feasibility (), dual feasibility (), and crucially complementary slackness : for each constraint, either it is tight (, boundary touched) or its multiplier is zero (, constraint slept through the whole problem). One of them must vanish, never both non-zero.
In our SVM, the constraints are . Complementary slackness will tell us that, at the optimum, only the points on the margin (where the constraint is tight) get non-zero . Everything else — the support-vector property, the sparsity, the kernel trick — flows from this single observation.
The Lagrangian and the dual
One multiplier per constraint:
Standard form for a minimisation with inequality constraints is . Here , so , explaining the minus sign. Each is a “tension” pulling the boundary away from the -th constraint.
Setting and gives two stationarity conditions:
The first equation is profound: the optimal weight vector is a linear combination of the (transformed) training points, weighted by signed dual variables. This is the form that makes the kernel trick work. Substitute it back into and we obtain the dual:
Crucial fact: features have vanished. The data only appear through the kernel . Choose any Mercer kernel and the algorithm just works — even when is infinite-dimensional.
Primal vs dual — which one do you actually solve?
The primal has variables (one per feature, plus the bias). The dual has variables (one per training point). Two regimes:
Solve the primal when
, and you use a linear kernel (or none). The decision function evaluates in regardless of how many training points you had. Linear solvers like LIBLINEAR are primal-based.
Solve the dual when
You want a non-linear kernel — full stop. The primal involves explicitly; if is high- or infinite-dimensional (RBF) you simply cannot write down. The dual only ever evaluates , which is finite and cheap. LIBSVM, SMO and friends are dual-based.
Either way, both problems have the same global optimum — strong duality holds because the primal is a convex QP with linear constraints — so the choice is purely about computational convenience.
KKT conditions and the meaning of support vectors
Because the primal has inequality constraints, the optimum satisfies the Karush–Kuhn–Tucker conditions:
The third equation is complementary slackness. For each point either the multiplier vanishes or the constraint is active — never both non-zero.
That last condition splits the training set into two camps:
- — the point is strictly outside the margin. It does not contribute to . Throw it away and the model is unchanged.
- — the point lies exactly on the margin, . These are the support vectors.
The prediction for a new point is a weighted vote of similarities to the support vectors only:
is the set of support-vector indices. The bias is recovered by averaging over support vectors using the fact that they satisfy exactly.
A short tour of kernels
Any function writable as for some feature map is a valid kernel. The technical test is Mercer’s condition: the Gram matrix must be symmetric and positive semi-definite for every finite sample. When this holds, the dual QP stays convex and the kernel is a drop-in replacement for the inner product. Three kernels cover the vast majority of practical use:
Linear
. No transformation — just the dot product. Use when data is already separable in input space, or when is huge (e.g. bag-of-words text). Cheapest and easiest to interpret: lives in the same space as the data.
Polynomial
. Lifts into the space of all monomials up to degree — so the boundary can be a degree- polynomial in the original features. Good for explicit feature interactions. The “+1” includes lower-degree terms.
RBF (Gaussian)
. The default workhorse. Implicitly maps into an infinite-dimensional space. The width controls how “local” the similarity is: small smooth boundaries; large tightly localised, risks overfitting.
How to choose
Default to RBF and cross-validate and on a 2-D log-spaced grid (the textbook recipe). Use Linear when — there is no benefit in lifting further, and it scales much better. Use Polynomial when domain knowledge tells you feature interactions of a known degree matter (e.g. degree-2 for physics features that combine multiplicatively). The kernel is a prior about what “similar” means — choose it like you would choose a model class.
Soft margin — letting some points misbehave
Real data is rarely perfectly separable. Two points overlap, a stray outlier sits on the wrong side — and the hard-margin problem becomes infeasible. The fix: introduce one non-negative slack variable per point, allowing it to violate the margin condition, and penalise the total violation:
controls the cost of violating the margin. Large almost hard margin (low bias, high variance). Small wider margin tolerating more violations (high bias, low variance). is chosen by cross-validation (Ch. 04).
Repeating the Lagrangian dance with slacks yields the soft-margin dual — identical to the hard-margin dual except that the multipliers are now bounded:
Compare with the hard-margin dual: only one change — the box constraint . The cap is the entire mathematical incarnation of “we tolerate some violations”.
The KKT analysis now classifies each training point into one of three regimes:
Not a support vector — outside the margin, safe
The point sits strictly on the correct side, beyond the margin. The constraint is not active and the slack is zero.
Margin support vector — sitting on the margin
The point lies exactly on the dashed line. It actively shapes the boundary but does not violate it. Used to compute the bias .
Bounded support vector — inside or misclassified
The constraint is violated; the multiplier is saturated at . If the point is on the correct side but inside the corridor; if it is on the wrong side outright.
Soft margin in one sentence
“Maximise the margin and minimise the total margin violation, balanced by .” In Ch. 04 language this is structural risk minimisation: the term is the capacity penalty, the term is the empirical risk, and is the bias–variance dial.
The hinge-loss view — SVMs as regularized loss minimization
Here is the perspective that ties SVMs into the rest of supervised learning. Look again at the soft-margin slack: . Why the max? Because the constraint is and , and the objective wants as small as possible — so it picks the larger of zero and the gap. That function has a name:
Zero when the point is correctly classified with margin at least 1; grows linearly as the point drifts inside the margin or across it.
Substituting back, the entire soft-margin SVM becomes the unconstrained minimisation
Same problem, no slacks. The structure is identical to ridge regression: a quadratic regularizer plus a per-example loss, balanced by a hyperparameter.
This view unlocks three things at once:
- SVMs are not exotic. They sit on the same shelf as ridge regression (squared loss + L2) and L2-regularized logistic regression (log loss + L2). Only the loss differs.
- The hinge is why SVMs are sparse. Unlike the squared or log losses, the hinge is exactly zero for any point comfortably on the right side. Those points contribute nothing to the gradient — and nothing to the model. Compare to logistic regression, which gives every point a non-zero (if tiny) say.
- is the inverse of the more familiar . Divide by and the equivalent form is . Large small weak regularization, narrow margin. Small large strong regularization, wide margin.
You can play with the hinge against the 0/1, squared, and logistic losses in Hands-on 3 below.
04 · Worked example
A four-point hard-margin SVM, by hand
We solve a tiny SVM end to end, getting explicit numbers for , , , and the margin. The numbers are friendly enough to verify each step on paper. Four points in two dimensions, two per class:
| 1 | ||
| 2 | ||
| 3 | ||
| 4 |
The positives sit up to the right, the negatives down to the left — clearly linearly separable. We use the linear kernel , no feature map.
1 · Guess the geometry first
Eyeball the four points. The two classes are stretched along the line . The natural separator runs perpendicular to it — so points along . The closest pair across the gap is and ; their midpoint is , so the boundary likely passes through with normal , i.e. the hyperplane .
2 · Identify the active constraints
Conjecture that the support vectors are the two closest points across the gap, and . For these the constraint is active: . Write (forced by symmetry) and solve. From :
From :
3 · Solve for w and b
Subtracting the second from the first:
So , and the decision function is
4 · Verify the non-active points
For : , and . ✓ For : , and . ✓ Both non-active constraints are satisfied with room to spare — confirming and are not support vectors and get .
5 · Compute the margin
The geometric margin is . Here , so the margin is . The corridor width is . Check: the distance from to is . ✓
6 · Recover α from the dual
Only and can be non-zero. Stationarity gives
so . The dual constraint gives , hence . Combined, , so and .
| Role | ||||
|---|---|---|---|---|
| 1 | margin SV | |||
| 2 | not SV | |||
| 3 | margin SV | |||
| 4 | not SV |
Map the example back to the formalism
- Decision function: .
- Margin: .
- Support vectors: and , with .
- Two of four training points contribute to the model. Throw away the rest and the predictions are identical — that is the sparsity property.
In larger problems you cannot guess the active set. The standard algorithm is SMO (Sequential Minimal Optimization): update two at a time while respecting the equality constraint . Updating one alpha alone would break this constraint — two is the smallest feasible step. Hands-on 1 runs exactly this solver on a few preset datasets.
05 · Visual explanation
The geometry of the margin
One figure earns its keep three times: the same diagram explains the primal, the dual, and the soft-margin extension. Read it slowly.
A · Hard-margin geometry. Three parallel lines. The middle one is — the decision boundary. The two dashed lines are — where the functional margin equals under the rescaling we imposed. The normal points perpendicular to the boundary, from the negative side to the positive side. The corridor width is , so minimising really does widen it. Only the points sitting on the dashed lines are support vectors; delete the rest and the corridor does not move. Explore this live in Hands-on 1.
B · Soft margin — the same picture with slack. Mix the classes slightly and some points end up where they “should not” be. Each carries a slack — the distance from where it sits to where it would need to be to satisfy the hard margin. Points with are on the correct side but inside the corridor; points with are misclassified. The objective pays for each. Adding slack invariably grows the SV set: the old margin SVs stay, and the new violating points join at .
C · The dial. acts on the soft margin the way acts on ridge regression — only in reverse. Large means “violations are expensive”: the algorithm shrinks the margin to satisfy almost every constraint, even if one outlier forces a contorted boundary. Small says “violations are cheap”: it prefers a wide, smooth corridor and accepts that some points end up inside. Drag the dial in Hands-on 2.
D · Kernels redraw the boundary
With a non-linear kernel, the same dual SVM produces a boundary that bends. The kernel implicitly maps the data into a higher (sometimes infinite-dimensional) feature space where a straight hyperplane lives; back in the original space, that hyperplane looks curved.
The left panel shows the original data — a ring of positives surrounded by negatives, definitely not linearly separable. The right panel sketches what an RBF kernel does conceptually: it “lifts” the data into a richer space where a straight hyperplane does the job. You never compute that lift explicitly — that is the whole point of the kernel trick.
Three lessons in one figure
(1) Margin is a corridor, not just a line. Widening it is the whole game. (2) Support vectors are the few points that pin the corridor; they live on the dashed boundaries (and, with soft margins, possibly inside or across them). (3) Kernels change the corridor’s shape, not the algorithm — the optimisation problem is identical; only the entry of the Gram matrix changes.
06 · Hands-on
Try it yourself
Three labs, each isolating one idea you need to see move before it sticks. Push the controls, watch the numbers, then read the takeaway.
Maximum-margin geometry — find the widest corridor
Each preset is a small, linearly separable dataset. The SVM solves its dual and returns the unique maximum-margin hyperplane (solid gold), the two margin lines y = ±1 (dashed), and the support vectors — the only points that touch the corridor, ringed in green. Far-away points get αₙ = 0 and could be deleted without changing the answer.
Soft margin — the C dial
The two classes overlap, so a hard margin is infeasible. The penalty C prices each margin violation ξₙ. Slide it from 10⁻² (wide corridor, many points inside it, calm boundary) to 10³ (narrow corridor, accuracy chased even at the cost of a contorted line). Terracotta stems mark each point's slack.
Hinge loss vs 0/1, squared, and logistic
The horizontal axis is the signed margin z = t·y(x): positive means correctly classified, and z ≥ 1 means correct with the full margin. Drag the probe to read each loss. The hinge (gold) is the tightest convex upper bound on the 0/1 loss that is flat past the margin — the property that makes SVMs sparse.
07 · Exam intel
What the exam actually tests
SVMs are a perennial Polimi favourite. A handful of question shapes account for almost every appearance.
Derive the primal from 'maximise the margin'
State the geometric margin . Use the rescaling freedom to fix the minimum functional margin to 1. Then , so maximising is minimising — equivalently . The constraints follow directly from the rescaling. State that the result is a convex QP — one global optimum.
Derive the dual
Write the Lagrangian , . Stationarity gives and . Substitute back to eliminate :
Highlight that only the kernel appears — this is what makes non-linear SVMs possible. State the dual is also a convex QP, with variables instead of (good when , e.g. kernels mapping to infinite-dimensional spaces).
State and use the KKT conditions
For the soft-margin SVM the KKT conditions are
From these derive the three regimes: (non-SV), (margin SV, ), (bounded SV, ). State how the bias is recovered from margin SVs: for any margin SV — or, for stability, average over all margin SVs.
Soft margin: derive the box constraint αₙ ≤ C
Add slacks and a penalty to the primal. The Lagrangian gains terms (with ), and the slack-margin constraint enters with multiplier . Stationarity in gives , i.e. . Together with this gives the box . The rest of the dual derivation is identical to the hard-margin case.
Generalisation bounds
Two bounds to memorise:
- Margin bound. The VC dimension of the class of separating hyperplanes with margin on data in a ball of radius is bounded by . Bigger margin smaller VC tighter generalisation gap. Loose in practice but conceptually crucial.
- Leave-one-out bound. . Data-dependent, requires no separate cross-validation, and is often what people quote in practice.
Both bounds explain why kernels can fail you: a very rich kernel makes all-vs-all points become SVs and both bounds go vacuous. The margin shrinks, the SV count explodes, and you overfit.
Rewrite the soft-margin SVM as regularized loss minimization
From the primal with , the two constraints on together force . So the SVM is the unconstrained problem — the same template as ridge regression (squared loss + L2) and L2-logistic regression (log loss + L2); only the loss differs. Here plays the role of : large = weak regularization.
When would you solve the primal vs the dual?
Primal has variables, dual has . Choose the primal when the feature map is explicit and cheap — linear kernel, , big datasets. Choose the dual when using a non-linear kernel: the primal may live in an infinite-dimensional space (RBF) and cannot be represented, while the dual only needs the finite Gram matrix . Strong duality holds (convex QP
- linear constraints) so the two give the same optimum.
Memorise these five formulas — and you have the chapter
- Primal: s.t. .
- Dual: s.t. .
- Prediction: .
- LOO bound: .
- Hinge-loss form: — same SVM, unconstrained, slots into the ridge / logistic-regression family.
08 · Common mistakes
Where students get this wrong
'Support vectors are the points closest to the boundary'
Half right. Support vectors are the points with non-zero . In the hard-margin case these are exactly the points on the margin (closest to the boundary, distance ). In the soft-margin case they also include points inside the margin and across it — anywhere the constraint is active or violated. A point can be a support vector despite being misclassified.
Forgetting to scale features before training
SVMs depend on Euclidean distances — through in the linear case and through kernel evaluations like in the RBF case. If one feature is in metres and another in kilograms, the metres feature dominates everything. Always standardise (zero mean, unit variance) before fitting. This is not optional; it changes the boundary.
'C is a regulariser, so larger C means more regularisation'
Backwards. Larger penalises violations more heavily, so the algorithm allows fewer violations and shrinks the margin — that is less regularisation. Small lets the margin be wide at the cost of more slack — that is more regularisation. Mentally connect: large small (in ridge-regression language).
'The dual has N variables, so it is always slower than the primal'
Depends on which is bigger, or . When — text classification with bag-of-words, or any kernel method where is high- or infinite-dimensional — the dual is vastly cheaper. When , the primal can be faster. SVMs are usually solved in the dual because the kernel trick demands it; SMO was designed specifically for this.
Using accuracy alone to choose the kernel and C
A 99% training accuracy can hide a fragile model with 80% of points as support vectors. Use cross-validated accuracy on a held-out set (or the LOO bound). The kernel and are model-selection parameters and must be tuned exactly like in ridge regression (Ch. 04).
Treating SVMs as black boxes after computing accuracy
Two diagnostics are free and very informative: the fraction of support vectors and the distribution of . If 80%+ of points are SVs, your kernel is too rich or too large — overfitting. If is small for nearly everyone, the data is well-separated and you could probably reduce . Look at the numbers before believing the accuracy.
'SVMs only do classification'
The same margin-maximisation idea works for regression (Support Vector Regression, with an -insensitive loss), novelty detection (one-class SVM), ranking, feature selection, and even semi-supervised learning. The chapter focuses on classification because the geometry is cleanest there — but the optimisation framework is much more general.
09 · Self-check
Can you answer these?
Seven questions in the style the exam likes. Click an option for instant feedback.
A trained hard-margin SVM has 200 training points; only 5 have non-zero αₙ. You add a new training point well inside positive territory (far from the boundary), retrain, and ask: which is true?
In the soft-margin dual, what is the meaning of a training point with αₙ = C?
You train an RBF SVM and observe that 90% of training points are support vectors. Train accuracy is 100%. What is most likely?
In the hard-margin SVM, the optimum satisfies w = Σₙ αₙ tₙ φ(xₙ). Which statement about this equation is FALSE?
You can write the soft-margin SVM as min ½‖w‖² + C Σₙ max(0, 1 − tₙ y(xₙ)). Which statement about this view is MOST accurate?
You train an SVM on text with N = 5,000 documents and D = 50,000 sparse TF-IDF features, using a linear kernel. Which approach is most appropriate?
Two hyperplanes both separate the data perfectly. Hyperplane A has γ = 0.2; hyperplane B has γ = 0.8 on data inside a ball of radius R = 1. Which generalises better, and why?
10 · Recap
One-screen summary
Chapter 07 — load-bearing ideas
- The maximum-margin hyperplane. Among all separating hyperplanes, pick the one with the widest empty corridor. Geometric margin after the standard rescaling.
- Hard-margin primal. subject to . Convex QP, unique global optimum, requires linear separability.
- Hard-margin dual. subject to . Features have vanished; only the kernel appears.
- KKT and support vectors. Complementary slackness partitions the data: most points have (non-SVs); a few sit on the margin with (SVs). The model depends only on SVs.
- Soft-margin SVM. Add slacks and penalty . Dual is identical except . Three regimes: outside-margin (), on-margin (), inside/across ().
- Kernel trick. Replace with any Mercer kernel . Linear, polynomial, RBF — all just different Gram matrices. The optimisation stays convex.
- Prediction. . Recover by averaging over margin SVs.
- Generalisation. Margin bound: VC . LOO bound: — free, data-dependent, often quoted in practice.
- Hinge-loss view. Soft-margin SVM . Same template as ridge and logistic regression; only the loss differs. The hinge’s flat tail past the margin is exactly what creates sparsity in .
- Primal vs dual. Primal has variables — solve when and the kernel is linear. Dual has variables — solve whenever the kernel is non-linear (RBF, polynomial). Strong duality means the same optimum either way.
Looking ahead → Chapter 08
We have built the cleanest convex classifier in the book. Next we leave convexity behind for models that stack non-linear transformations — neural networks — where the loss surface is riddled with local minima but the representational power is unmatched.