COMP328 Fundamentals of Machine Learning
  1. Read the tutorials
  2. Run the notebook
  3. Check yourself
  4. Quiz 9
  5. 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 SVC models with scikit-learn.
  • Build a pipeline that scales features before fitting — essential for SVMs.
  • Use a grid search to select C and gamma with 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.

04 Topics & Key Concepts

Unit 9 syllabus topics mapped to tutorials and outcomes
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 C punishes violations harshly (narrow margin, overfitting risk); small C tolerates 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 by gamma.
Gamma (γ)
The RBF kernel's reach parameter. Large gamma means each point influences only its immediate neighbourhood (wiggly boundary); small gamma means 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.

Four-point dataset, linearly separable
Point Coordinates (x, y) Class
P1(1, 1)+1
P2(2, 2)+1
N1(−1, −1)−1
N2(−2, −2)−1

Step-by-step

  1. 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| = 1 gives:
    w = (0.5, 0.5),  b = 0
  2. Evaluate the decision function f(x) = w·x + b at 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
  3. 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.

  4. 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
  5. Verify geometrically. The perpendicular distance from P1 to the boundary x + y = 0 is:
    |1 + 1| / √(1² + 1²) = 2 / √2 = √2 ≈ 1.414
    
    Total margin = 2 × 1.414 = 2√2 ≈ 2.828  ✓
    The two calculations agree.
  6. Test the boundary's robustness. Now add a fifth point, P3 = (5, 5), to the positive class. ReComputing the decision function gives f(P3) = 5.0. Since this is well beyond the margin, P3 is not a support vector and the boundary does not move.
  7. Introduce a violation. Instead add P3 = (0.5, 0.5). Now f(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 to C. 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).

  1. Propose a weight vector w and bias b that satisfy |w·x + b| = 1 at the support vectors.
  2. Evaluate the decision function at all four points and identify the support vectors.
  3. Compute ‖w‖ and the margin 2/‖w‖.
  4. 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.

  1. Which value produces the widest margin?
  2. Which value misclassifies the most training points?
  3. 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.

  1. Report test accuracy for both.
  2. Sketch or screenshot both decision boundaries.
  3. Write three sentences explaining why the linear kernel fails here, and what the RBF kernel is doing differently.

Notebook

u09-support-vector-machines.ipynb Guided notebook — visualise margins, sweep 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
Only the support vectors. The optimisation depends solely on the examples that lie on or violate the margin. Points sitting comfortably outside it can be removed without changing the boundary at all — which is why an SVM's prediction cost scales with the number of support vectors, not the size of the training set.

Question 2 of 3

You increase the RBF kernel's gamma from 0.01 to 10. What happens to the decision boundary?

Show answer
It becomes more wiggly. A large 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
To compute a high-dimensional dot product without explicitly transforming the features. The SVM's dual formulation depends only on dot products between examples. A kernel function evaluates what that dot product would be in a higher-dimensional space, at the cost of a simple closed-form calculation in the original space. This lets a linear method produce non-linear boundaries — and for the RBF kernel, without ever materialising the (infinite-dimensional) feature space at all.

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. Large C fits the training data closely; small C prefers 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 SVC in a pipeline with StandardScaler.
  • 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.

Ready to find the widest margin?

Start with the geometry of hyperplanes and margins, then work through the hand-computed maximum-margin example that makes the whole method click.

👤