Module 3 · Unit 9
Support Vector Machines
Where a decision tree asks "which question separates the data best?", a support vector machine asks a geometric question: "which boundary leaves the widest possible gap between the classes?" This unit develops that idea from the ground up — hyperplanes, margins, support vectors — and then shows how the kernel trick lets a linear method draw remarkably non-linear boundaries.
Supervised learning Maximum margin Kernel methods Unit 9 of 20 ≈ 5 hours 8 tutorials
- Read the tutorials
- Run the notebook
- Check yourself
- Quiz 9
- Module 3 review
01 Learning Outcomes
Knowledge
- Define a hyperplane and explain how it acts as a linear decision boundary.
- Explain the margin and why maximising it improves generalisation.
- Identify support vectors and explain why only they determine the boundary.
- Distinguish a hard margin from a soft margin and explain the role of slack variables.
- Describe the effect of the C parameter and the gamma parameter on model complexity.
- Explain the kernel trick — how an implicit mapping to a higher-dimensional space enables non-linear boundaries without explicit computation.
- Compare linear, polynomial, and RBF kernels and state when each is appropriate.
Skills
- Compute decision-function values and identify support vectors for a small 2-D dataset.
- Calculate the geometric margin from the weight vector using
2 / ‖w‖. - Train, tune, and evaluate
SVCmodels with scikit-learn. - Build a pipeline that scales features before fitting — essential for SVMs.
- Use a grid search to select
Candgammawith cross-validation. - Visualise decision boundaries and margins in two dimensions.
Professional Competencies
- Recognise that SVMs are not interpretable in the way trees are, and communicate that trade-off honestly.
- Explain why feature scaling is a correctness requirement, not an optional refinement, for distance-based models.
- Anticipate scaling and latency costs when considering an SVM for production deployment.
- Report class-imbalance handling (via
class_weight) transparently in a model card.
02 Why This Unit Matters
Units 7 and 8 built models that partition feature space with axis-aligned cuts. Support vector machines take a fundamentally different approach: they look for the single boundary that separates the classes with the largest possible safety margin. That geometric objective turns out to be far more robust than it first appears, and it generalises to boundaries that are not straight lines at all.
SVMs also introduce two ideas that recur throughout machine learning. The first is that only a few training points matter — the ones nearest the boundary. The second is the kernel trick, a mathematical shortcut that lets a linear algorithm behave non-linearly. Both reappear in later units and in modern deep learning.
Big idea
Among all the boundaries that separate two classes perfectly, prefer the one with the widest margin. A boundary that sits far from every training point is less likely to be nudged into error by a new, unseen point.
Where you have already met this
Unit 6's bias–variance trade-off shows up here as the C parameter.
A large C insists on classifying every training point correctly —
low bias, high variance. A small C tolerates some mistakes in
exchange for a wider, smoother margin — higher bias, lower variance.
Common misconception
"SVMs are always more accurate than trees." Not true. SVMs excel on moderate-sized, well-scaled datasets with clear geometric structure — especially when the number of features is large relative to the number of rows. On large, messy, mixed-type tabular data, a random forest will often match or beat them, with far less tuning.
03 Reading Roadmap
Work through the eight tutorials in order. Tutorials t-01 and t-02 establish the geometry; t-03 relaxes it to handle real, non-separable data; and t-04 introduces the kernel trick, which is the conceptual highlight of the unit. Take the hand calculations in t-02 slowly — they make everything afterwards concrete.
Hyperplanes & the Margin
Linear decision boundaries, the weight vector, and the geometric meaning of distance to a plane.
t-02Maximum Margin Classification
Support vectors, the margin formula 2/‖w‖, and a full hand-worked 2-D example.
Soft Margins & the C Parameter
Slack variables, hinge loss, and how C trades margin width against training errors.
The Kernel Trick
Why an implicit high-dimensional mapping lets a linear method draw curved boundaries.
t-05Choosing a Kernel
Linear, polynomial, and RBF kernels; the role of gamma; and practical selection rules.
SVMs in scikit-learn
SVC, pipelines with StandardScaler, and grid search over C and gamma.
High Dimensions & Support Vectors
Why SVMs thrive when features outnumber samples, and how to inspect support vectors.
t-08Strengths, Limits & Fairness
Scaling requirements, computational cost, class imbalance, calibration, and responsible use.
04 Topics & Key Concepts
| Topic | What you will be able to do | Tutorials |
|---|---|---|
| Hyperplanes | Write the equation of a linear decision boundary and evaluate its decision function. | t-01 |
| Maximum margin | Identify support vectors, compute the margin, and explain why a wider margin generalises better. | t-01, t-02 |
| Soft margins | Relax the separable assumption with slack variables and tune the trade-off using C. |
t-03, t-06 |
| Kernel methods | Explain the kernel trick and choose between linear, polynomial, and RBF kernels. | t-04, t-05 |
| High-dimensional data | Recognise when SVMs have an advantage and inspect the learned support vectors. | t-07, t-08 |
Terms you must be able to define
- Hyperplane
- A flat decision boundary of one dimension fewer than the feature space. In 2-D it is a line; in 3-D it is a plane. Written as
w·x + b = 0. - Weight vector (
w) - The vector normal (perpendicular) to the hyperplane. Its direction sets the orientation of the boundary; its length controls the margin.
- Margin
- The distance between the decision boundary and the nearest training points on either side. The SVM's objective is to maximise it.
- Support vectors
- The training points that lie exactly on the margin — the ones that satisfy
|w·x + b| = 1. Only these points determine the boundary; removing any other point leaves it unchanged. - Hard margin
- A formulation that requires every training point to be classified correctly and lie outside the margin. Only possible when the data are linearly separable.
- Soft margin
- A formulation that permits margin violations at a cost. Used for almost all real datasets.
- Slack variable (
ξ) - A per-example allowance for how far a point may intrude into the margin or cross the boundary. Zero for well-classified points outside the margin.
- C parameter
- The penalty for total slack. Large
Cpunishes violations harshly (narrow margin, overfitting risk); smallCtolerates them (wide margin, underfitting risk). - Hinge loss
- The loss function
max(0, 1 − y(w·x + b)), which is zero for correctly classified points outside the margin and grows linearly for violations. - Kernel trick
- Rewriting the SVM optimisation so it depends only on dot products between examples, then substituting a kernel function
K(xᵢ, xⱼ)that implicitly computes a dot product in a higher-dimensional space. - RBF (Gaussian) kernel
K(xᵢ, xⱼ) = exp(−γ‖xᵢ − xⱼ‖²). Maps to an infinite-dimensional space and can produce arbitrarily curved boundaries. Controlled bygamma.- Gamma (
γ) - The RBF kernel's reach parameter. Large
gammameans each point influences only its immediate neighbourhood (wiggly boundary); smallgammameans influence reaches further (smooth boundary).
05 Worked Example: Finding the Maximum Margin by Hand
Consider a small, perfectly separable 2-D dataset. The positive class contains two
points and the negative class contains two points, arranged symmetrically along the
line y = x.
| Point | Coordinates (x, y) | Class |
|---|---|---|
| P1 | (1, 1) | +1 |
| P2 | (2, 2) | +1 |
| N1 | (−1, −1) | −1 |
| N2 | (−2, −2) | −1 |
Step-by-step
-
Choose the orientation. The two classes lie on opposite sides
of the line
x + y = 0, so a sensible weight vector points along(1, 1). Normalising so that support vectors satisfy|w·x + b| = 1gives:w = (0.5, 0.5), b = 0 -
Evaluate the decision function
f(x) = w·x + bat every training point:P1 (1, 1): 0.5(1) + 0.5(1) = 1.0 P2 (2, 2): 0.5(2) + 0.5(2) = 2.0 N1 (−1, −1): 0.5(−1) + 0.5(−1) = −1.0 N2 (−2, −2): 0.5(−2) + 0.5(−2) = −2.0 -
Identify the support vectors. The points whose decision value
has magnitude exactly 1 are P1 and N1. P2 and N2 have larger
magnitudes — they sit comfortably outside the margin and impose no constraint.
Key insight
Only P1 and N1 determine the boundary. You could delete P2 and N2 from the dataset and retrain: the SVM would return the identical hyperplane. This sparsity is what makes SVMs memory-efficient at prediction time — only the support vectors need to be stored.
-
Compute the margin. The margin is the distance between the two
supporting hyperplanes, given by
2 / ‖w‖:‖w‖ = √(0.5² + 0.5²) = √0.5 ≈ 0.7071 Margin = 2 / 0.7071 ≈ 2.828 -
Verify geometrically. The perpendicular distance from P1 to the
boundary
x + y = 0is:
The two calculations agree.|1 + 1| / √(1² + 1²) = 2 / √2 = √2 ≈ 1.414 Total margin = 2 × 1.414 = 2√2 ≈ 2.828 ✓ -
Test the boundary's robustness. Now add a fifth point,
P3 = (5, 5), to the positive class. ReComputing the decision function givesf(P3) = 5.0. Since this is well beyond the margin, P3 is not a support vector and the boundary does not move. -
Introduce a violation. Instead add
P3 = (0.5, 0.5). Nowf(P3) = 0.5, which is inside the margin and on the wrong side of the supporting hyperplane. Perfect separation is no longer possible with this orientation, so the SVM must either reorient the boundary or — with a soft margin — absorb the violation into the slack variableξ, paying a penalty proportional toC. This is exactly the trade-off that Tutorial t-03 develops.
Why scaling matters — a preview
The margin was computed from ‖w‖, which treats every feature
dimension equally. If one feature were measured in thousands and another in
decimals, the distance calculation would be dominated by the large-scale feature
and the "maximum margin" would be meaningless. Always standardise features
before fitting an SVM. Tutorial t-06 shows the pipeline that does this
correctly.
06 Learning Activities
Activity 9.1 — Compute a margin from scratch
Consider the dataset: positive points at (2, 0) and (3, 0);
negative points at (−2, 0) and (−3, 0).
- Propose a weight vector
wand biasbthat satisfy|w·x + b| = 1at the support vectors. - Evaluate the decision function at all four points and identify the support vectors.
- Compute
‖w‖and the margin2/‖w‖. - Verify your margin by Computing the perpendicular distance from a support vector to the boundary and doubling it.
Activity 9.2 — Trace the effect of C
In the notebook, fit three RBF-kernel SVMs to the same two-dimensional dataset
using C = 0.01, C = 1, and C = 100. Plot the
decision boundary and margin for each.
- Which value produces the widest margin?
- Which value misclassifies the most training points?
- Compare training accuracy and cross-validated accuracy for each. Which value would you deploy, and why?
Activity 9.3 — Linear versus RBF on a non-separable problem
Generate a two-dimensional dataset with two interleaved crescent shapes
(make_moons with noise). Fit an SVM with a linear kernel and one with
an RBF kernel, both with default C.
- Report test accuracy for both.
- Sketch or screenshot both decision boundaries.
- Write three sentences explaining why the linear kernel fails here, and what the RBF kernel is doing differently.
Notebook
C and gamma, compare kernels, and inspect support vectors.
Open
The core of the notebook is a scaled pipeline with a grid search:
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import GridSearchCV
# Scaling is not optional for SVMs — it is part of the model.
pipe = make_pipeline(
StandardScaler(),
SVC(kernel="rbf", probability=True, random_state=42),
)
param_grid = {
"svc__C": [0.1, 1, 10, 100],
"svc__gamma": ["scale", 0.01, 0.1, 1],
}
search = GridSearchCV(pipe, param_grid, cv=5, scoring="f1", n_jobs=-1)
search.fit(X_train, y_train)
print("Best params:", search.best_params_)
print("Best CV F1: ", round(search.best_score_, 3))
best = search.best_estimator_
print("Support vectors per class:", best[-1].n_support_)
Never skip the scaler
Fitting SVC directly on unscaled features is one of the most common
mistakes in applied machine learning. It rarely throws an error — it simply
produces a quietly worse model. If you remember one practical rule from this unit,
make it this one.
07 Self-Check
Answer these before moving on. If any feel uncertain, revisit the linked tutorial.
Quick check — 3 questions
Question 1 of 3
Which training points determine the position of an SVM's decision boundary?
Show answer
Question 2 of 3
You increase the RBF kernel's gamma from 0.01 to 10. What happens
to the decision boundary?
Show answer
gamma means each
training point's influence decays quickly with distance, so the boundary
contorts to accommodate individual points — a classic overfitting signature.
A small gamma extends each point's reach, producing a smoother,
more global boundary. Together, C and gamma are the
two knobs you tune for an RBF SVM.
Question 3 of 3
What is the main purpose of the kernel trick?
Show answer
08 Assessment Activities
3%
Quiz 9 · Support Vector Machines
12 questions covering hyperplane geometry, margin computation, support vectors,
the C and gamma parameters, kernel selection, and the
role of feature scaling. Unlimited attempts; highest score counts.
12%
Module 3 Review · Classical Algorithms
A comparative analysis across decision trees, random forests, and SVMs on a single dataset. Requires justified model selection, honest reporting of costs and limitations, and a recommendation for deployment.
- Quiz 9 Support Vector Machines — 12 questions, auto-graded Due end of week 9
- Module 3 Review Tree vs forest vs SVM — comparative report Due week 10
- Capstone Justify your choice of algorithm family for your capstone problem End of course
Tip for the Module 3 Review
Resist the temptation to declare a single "best" algorithm. A strong report shows that the answer depends on the data: report accuracy and training time, inference latency, sensitivity to scaling, and interpretability for each of the three model families. The recommendation should follow from those trade-offs, not from the headline metric alone.
09 Summary
What you should take away
- An SVM finds the hyperplane that maximises the margin between two classes. A wide margin means the boundary sits far from the training data, which improves generalisation.
- Only the support vectors — the points on or inside the margin — determine the boundary. Everything else is irrelevant to the solution.
-
Real data are rarely perfectly separable, so the soft margin
formulation introduces slack variables and a penalty controlled by
C. LargeCfits the training data closely; smallCprefers a wide, tolerant margin. -
The kernel trick replaces explicit dot products with a kernel
function, letting a linear algorithm produce non-linear boundaries. The
RBF kernel is the usual default, tuned through
gamma. -
Feature scaling is mandatory. Because the margin is a geometric
distance, features on different scales distort it. Always wrap
SVCin a pipeline withStandardScaler. - SVMs shine on moderate-sized, high-dimensional, well-scaled problems. They are not a universal replacement for trees, and their lack of interpretability is a real cost in regulated settings.
Next up
That completes Module 3 — three very different approaches to supervised learning, united by the bias–variance trade-off. Module 4 turns to unsupervised learning, beginning with Unit 10, Clustering, where the goal is no longer prediction but discovering structure in unlabelled data.