Machine Learning Slides 📂 Introduction · 13 of 17 54 min read

Support Vector Machines Explained — Margins, Kernels, C & γ Tuning

A visual, beginner-friendly guide to Support Vector Machines. Learn maximum-margin classification, why only support vectors matter, hard vs soft margins with the C parameter, the kernel trick that turns linear models non-linear, the four common kernels (Linear, RBF, Polynomial, Sigmoid), the γ parameter, hinge loss, SVR for regression, sklearn implementation, common pitfalls and seven golden rules for practitioners.

🛡️

Support Vector Machines

The classifier that draws the widest possible aisle between classes — maximum margins, support vectors, and the kernel trick that lets a linear model curve through non-linear data.
Maximum Margin Support Vectors Kernel Trick C & γ Tuning

Press Next → or use ← → arrow keys

Section 01

What Is A Support Vector Machine?

The town planner drawing the widest possible road between two neighbourhoods
Two neighbourhoods sit on either side of a stretch of land. A town planner could draw any line to divide them — but the sensible choice is the line that leaves the widest possible buffer on both sides. Future residents building near the boundary will still comfortably fall into their correct neighbourhood.

A Support Vector Machine does exactly this. It hunts for the separating boundary that maximises the empty gap (the margin) between the two classes. A wide margin means more confidence — and better generalisation to new data.
💡
The Working Definition

SVM is a supervised classifier that finds the maximum-margin hyperplane — the boundary with the largest possible distance from the nearest points of each class. Those nearest points are called support vectors, and they alone determine the whole model.

‖w‖Width = 2 / ‖w‖ · maximise
SVSupport vectors only
C & γTwo dials that matter
KernelCurved boundaries · linear math
Section 02

The Maximum-Margin Hyperplane

Feature 1 → Feature 2 → margin = 2 / ‖w‖ hyperplane · w·x + b = 0 w·x + b = +1 w·x + b = −1 ← support vector
🎯
Support Vectors Do All The Work

Only the points touching the two margin lines matter — they are the support vectors. Delete every other training point (98% of them, sometimes) and retrain — you get the exact same model. That's why SVMs are so memory-efficient at inference time.

Section 03

The Math In Four Lines

The Hyperplane
w · x + b = 0
w is perpendicular to the boundary. b shifts it. Together they define the divide.
Classification Rule
ŷ = sign( w · x + b )
Positive side → class +1. Negative side → class −1. That's the entire prediction step.
Optimisation Objective
minimise ½ ‖w‖² + C · Σ ξᵢ
Shrink ‖w‖ (widen the margin) while paying C per unit of margin violation.
Margin Constraint
yᵢ · (w · xᵢ + b) ≥ 1 − ξᵢ
Every point must sit at least on its margin line, unless it pays a slack penalty ξᵢ.
📐
Why "Support" Vectors?

Only the points that sit exactly on the margin lines (or violate them with a slack ξᵢ > 0) influence w and b. Every other point contributes zero to the solution — hence "support" vectors: the tiny subset of the data that holds the whole hyperplane up.

Section 04

Hard Margin vs Soft Margin — The C Trade-Off

Hard Margin (high C) zero violations · narrow gap · fragile tight fit · one noisy point ruins everything Soft Margin (moderate C) wide gap · few slack violations · robust 1 slack violation OK · generalises much better
C valueBehaviourSymptom
C = 100Narrow margin · zero toleranceOverfits · one noisy point moves the line
C = 1.0Balanced · few slack violations allowedUsually the sweet spot
C = 0.001Very wide margin · many violations OKUnderfits · misses real patterns
🎚️
Think Of C As "How Much Do Mis-classifications Hurt?"

Real data is messy — perfect separation isn't feasible. Soft-margin SVM lets a few points cross the boundary by paying a slack cost. C sets the price. High C → strict. Low C → forgiving. Always tune on a log grid.

Section 05

The Kernel Trick — Curved Boundaries, Linear Math

2D · original space no straight line can separate any straight line fails φ(x) lift to 3D Higher-D · lifted space a flat plane now separates a flat plane cleanly separates them
The Trick — Never Compute The Lift Explicitly

Actually mapping every point into a high-dimensional space would be prohibitively expensive. The kernel trick uses a clever identity — K(xᵢ, xⱼ) = φ(xᵢ) · φ(xⱼ) — that computes the dot product as if the points had been lifted, without ever performing the lift. Non-linear boundaries at linear-model cost.

Section 06

The Four Kernels You'll Use

Linear xᵢ · xⱼ text · sparse · high-dim RBF · Gaussian exp(−γ‖xᵢ−xⱼ‖²) default · non-linear go-to Polynomial (γ xᵢ·xⱼ + r)ᵈ interactions · vision · NLP Sigmoid tanh(γ xᵢ·xⱼ + r) rarely used · often unstable
KernelBest ForWatch Out For
LinearText, TF-IDF, wide sparse featuresStraight lines only — can't curve
RBF (default)Any non-linear problemSensitive to γ — needs tuning
PolynomialFeature interactions, image dataOverflows on high degrees
SigmoidRarely a first choiceUnstable · often doesn't converge
Section 07

The γ Parameter — Reach Of Each Support Vector

γ = 0.01 · very smooth underfits · misses structure high bias γ = 'scale' · balanced captures pattern · generalises sweet spot ✅ γ = 100 · jagged overfits · islands around each point high variance · memorised
🎛️
C And γ Interact — Tune Them Together

Always use gamma='scale' as your default (it adapts to feature variance). Never tune C alone — the two parameters push and pull each other. Sweep both on a log grid {0.001, 0.01, 0.1, 1, 10, 100} via GridSearchCV and let CV pick the winner.

Section 08

Hinge Loss — Only Punish The Wrong Side

−2 −1 0 +1 +2 y · (w·x + b) → score loss → margin edge wrong side · linear penalty safely correct · zero loss
Hinge Loss Per Sample
L = max( 0, 1 − y · (w·x + b) )
Zero loss if correctly classified beyond the margin. Linear penalty otherwise.
Why Hinge — Not Log Loss?
focuses only on the boundary
Points far inside the correct zone don't influence training at all. That's what gives SVMs their support-vector sparsity.
Section 09

Beyond Binary — SVR & Multi-Class

📏
SVR — Regression
ε-insensitive tube
Fit a tube of width 2ε around the target. Points inside cost nothing; points outside pay a linear penalty. Great for smooth continuous targets.
🥊
One-vs-One (OvO)
k(k−1)/2 classifiers
Train one binary SVM for every pair of classes. Vote to pick the winner. sklearn's SVC default for multi-class.
🎯
One-vs-Rest (OvR)
k classifiers
Train k binary SVMs, each "this class vs everything else". Pick the class with highest confidence. Faster for many classes.
SVR Objective
minimise ½‖w‖² + C · Σ (ξᵢ + ξᵢ*)
Same margin idea as classification — but tolerance is a tube around the regression line, not a gap between classes.
One-Class SVM
outlier / novelty detection
Train on "normal" data only. Learn the boundary of the normal region. Anything falling outside is flagged as anomaly.
Section 10

Strengths & Weaknesses

📚
Great On High-Dim Sparse Data
TF-IDF vectors, genomics, one-hot encodings. Linear SVM is still a top text-classification baseline.
💾
Memory-Efficient
The trained model stores only support vectors — often a tiny fraction of the training data.
🎨
Versatile Via Kernels
Swap kernel, get linear, polynomial, RBF or custom boundaries — without changing the training algorithm.
🐢
Slow On Large Data
Training scales O(n²) to O(n³). Not practical past ~100k samples. Use SGDClassifier(loss='hinge') instead.
📏
Needs Feature Scaling
Distance-based. Skipping StandardScaler lets one large-scale feature dominate every margin.
📊
No Native Probabilities
SVM outputs scores, not probabilities. Set probability=True for Platt-scaled probabilities — slower to train.
🥊
SVM vs Logistic Regression vs Random Forest

Logistic Regression is faster and gives calibrated probabilities — often the safer default. Random Forest handles feature interactions natively and doesn't need scaling. SVM wins on wide sparse data (text) and when the margin idea genuinely helps generalisation. For under 10k samples with a clean signal, SVM with RBF still holds its own.

Section 11

Implementation — Sklearn In A Handful Of Lines

from sklearn.svm import SVC, LinearSVC, SVR
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
import numpy as np

# ── Classification with RBF · always scale + pipeline ─────────
svm = Pipeline([
    ('scaler', StandardScaler()),
    ('clf', SVC(kernel='rbf', C=1.0, gamma='scale', probability=True)),
])
svm.fit(X_train, y_train)

# ── Tune C AND γ together on a log grid ──────────────────────
grid = GridSearchCV(svm, param_grid={
    'clf__C':     np.logspace(-3, 3, 7),
    'clf__gamma': np.logspace(-4, 2, 7),
}, cv=5, scoring='roc_auc', n_jobs=-1).fit(X_train, y_train)
print(grid.best_params_, grid.best_score_)

# ── Text · LinearSVC scales far better than kernel SVC ───────
text = Pipeline([
    ('tfidf', TfidfVectorizer(ngram_range=(1, 2))),
    ('clf',   LinearSVC(C=1.0, max_iter=5000)),
]).fit(docs_train, y_train)

# ── Regression with ε-tube ───────────────────────────────────
svr = Pipeline([
    ('scaler', StandardScaler()),
    ('svr', SVR(kernel='rbf', C=100, epsilon=0.1)),
]).fit(X_train, y_train)
Two Non-Negotiable Rules

Always wrap in a Pipeline so the scaler refits per CV fold — no data leakage. Set probability=True at construction (not later) if you need calibrated probabilities; switching it on afterward means Platt scaling doesn't happen and predict_proba disagrees with predict.

Section 12

Where SVM Still Wins In Production

📧
Text Classification
Spam filtering, topic categorisation, sentiment analysis. LinearSVC on TF-IDF is still a top-3 baseline.
🧬
Bioinformatics
Gene expression, protein classification — high-dimensional data with few samples. Perfect SVM territory.
📸
Image Recognition
Face detection with HOG features, handwriting classification on small datasets. Pre-deep-learning workhorse.
💳
Fraud & Anomaly Detection
One-Class SVM for novelty detection when only "normal" data is available. Common in security and finance.
🏥
Medical Diagnosis
Small clean datasets with interpretable features. Handwritten digit classification, tumour detection with radiomics.
🎓
Benchmarks & Kaggle
Still a common baseline in ML research. If your fancy model can't beat SVM+RBF, the fancy model has a problem.
Section 13

Common Pitfalls — What Silently Breaks SVM

📏
Skipping Feature Scaling
the #1 mistake
SVM is distance-based. Without StandardScaler, one large-scale feature swamps every margin calculation.
🎚️
Tuning C Without γ
they interact
Tuning one at a time misses the interaction. Sweep both on a log grid with GridSearchCV.
🐢
SVC On Huge Data
O(n²) training
Past ~100k samples, kernel SVC trains for hours. Use LinearSVC or SGDClassifier(loss='hinge').
📊
Wrong Probability Setup
probability=True later
Set it at construction. Turning it on afterward means predict_proba gives inconsistent answers.
🎯
gamma='auto' By Habit
use 'scale'
The 'scale' default (1 / (n_features · var)) works far better than the legacy 'auto' on almost every dataset.
🌀
Noisy Overlapping Classes
wrong tool
SVM struggles when classes truly overlap. Try gradient boosting or random forest — they handle noise more gracefully.
Section 14

Golden Rules — Seven Habits For SVM Practitioners

🛡️ SUPPORT VECTOR MACHINE DISCIPLINE
1
Always scale features first. Use StandardScaler inside a Pipeline. SVM is distance-based; skipping this step silently destroys the margin geometry.
2
Tune C and γ together on a log grid. Try {0.001, 0.01, 0.1, 1, 10, 100} for both via GridSearchCV. They push against each other — one at a time misses the interaction.
3
Default to gamma='scale'. It adapts to feature variance automatically. Only override if you're deliberately searching a grid.
4
LinearSVC for text and n > 10,000. SVC for the rest. Kernel SVMs get painfully slow on large datasets. LinearSVC scales linearly and is a text-classification classic.
5
Set probability=True at construction time. Enables Platt scaling for calibrated probabilities. Skipping it means decision_function scores are all you get — useful, but not probabilities.
6
Monitor the support-vector count. Every training point becoming a support vector = the model is memorising, not learning. A healthy fit uses a fraction of the data as support vectors.
7
Consider One-Class SVM for anomaly detection. When only "normal" data is available (fraud, defect detection, novelty), this is often the go-to model. Compact, fast at inference, easy to reason about.
FINAL

SVM — The Elegant Classifier That Refuses To Retire

2 / ‖w‖Maximum margin
SVOnly support vectors matter
C, γTwo dials to tune
K(·)Kernels for non-linear
HingeLoss that ignores easy cases
7Golden rules
🎯
The Foundation Is Set

You now understand maximum-margin classification, why only support vectors matter, how the C parameter trades margin width for accuracy, how the kernel trick delivers non-linear boundaries at linear-model cost, and how γ shapes the RBF reach. Every SVM you tune from now on is a variation on these ideas.

📚
Where To Go Next

Study Kernel PCA (same kernel trick, unsupervised), then One-Class SVM & Isolation Forest for anomaly detection, then SGDClassifier(loss='hinge') for SVM at scale. Practise on the MNIST, 20 Newsgroups and Breast Cancer datasets — SVM excels on all three.

🛡️ End of tutorial · Press to review, or click Restart