Support Vector Machines
After this lesson, you will be able to:
- Understand the maximum margin idea — find the boundary between classes that leaves the widest gap, because wider gaps generalize better
- Know what support vectors are — the few critical data points sitting right at the edge of the gap that actually determine the boundary
- Understand the kernel trick — a clever math shortcut that lets SVMs draw curvy boundaries, not just straight lines
- Know when to use SVMs (small-to-medium data, clear margins) vs. trees or neural networks (large data, complex patterns)
- Tune the C and gamma hyperparameters and explain how they jointly control the margin width and boundary complexity
Before you start
Don't worry if "maximum margin" and "kernel trick" sound intimidating — an SVM is just drawing a line between two groups and making the gap as wide as possible, like painting the widest road you can between cats and dogs. The kernel trick just lets that road curve!
#The Widest Street Between Classes
#End-to-End: How an SVM Classifies
#Step 1: Plot Data Points in Feature Space
Each training example is a point in d-dimensional feature space, labeled as either positive (+1) or negative (-1). In 2D, you can visualize red dots and blue dots on a plane. The goal is to find a boundary that separates the two classes as cleanly as possible.
#Step 2: Find the Separating Hyperplane
Among all possible hyperplanes (straight lines in 2D) that correctly separate the classes, the SVM searches for the one that is positioned optimally. The hyperplane is defined by w^T x + b = 0. Points on one side are classified as positive, points on the other side as negative.
#Step 3: Maximize the Margin
The margin is the distance between the decision boundary and the nearest data points from each class. The SVM maximizes this margin by minimizing ||w||^2 subject to all points being correctly classified. A wider margin means the boundary is more robust to small perturbations in new data — better generalization.
#Step 4: Identify Support Vectors
The nearest points to the boundary, the ones that "support" the margin, are the support vectors. These are the only training points that determine the decision boundary. Remove any other point and the boundary does not change. This makes SVMs memory-efficient and robust to outliers far from the boundary.
#Step 5: Kernel Trick for Non-Linear Data
When classes are not linearly separable, the kernel trick maps data to a higher-dimensional space where a linear boundary exists. The RBF kernel computes dot products in an infinite-dimensional space without ever constructing it. In the transformed space, a linear SVM creates complex, non-linear decision boundaries in the original feature space.
#The Maximum Margin Objective
For linearly separable data, the SVM finds the hyperplane that maximizes the margin:
Try it! Open the Python REPL and type these lines yourself. Train an SVM and find the support vectors:from sklearn.svm import SVC; from sklearn.datasets import load_iris; X, y = load_iris(return_X_y=True); svm = SVC(kernel='linear').fit(X, y); print(f"Total points: {len(X)}, Support vectors: {len(svm.support_vectors_)}")— notice how few points actually matter!
Equivalently, this is minimizing ||w||^2 (a convex quadratic program):
The margin 2/||w|| and the switch from a maximum to a minimum both deserve a proof. Open the derivation to see where they come from.
Interactive Lab
Drag points to widen or shrink the margin. The amber-ringed support vectors are the ONLY ones that move the boundary — try dragging a non-support-vector point anywhere on its own side and watch the boundary not budge.
In the soft-margin SVM, increasing the C parameter does what to the margin width and the tolerance for misclassified training points?
#Support Vectors: The Only Points That Matter
A linear SVM is trained on 10,000 data points. It finds 15 support vectors. If you remove a non-support-vector point and retrain, what happens?
The decision boundary stays exactly the same. The SVM's solution depends only on the support vectors — the points closest to the boundary. The remaining 9,985 points could be anywhere on their correct side and the model would be identical. This is a beautiful mathematical property and makes SVMs very memory-efficient at prediction time (store only the support vectors).
#Worked Example: Maximum Margin on 4 Points
Imagine 4 labeled points in 2D:
| Point | x₁ | x₂ | Label |
|---|---|---|---|
| A | 1 | 1 | +1 |
| B | 2 | 1 | +1 |
| C | 1 | 4 | −1 |
| D | 2 | 5 | −1 |
x₂ = 2.5, but is it the maximum-margin boundary? The closest positive point (B) is at x₂ = 1; the closest negative point (C) is at x₂ = 4. Halfway between is x₂ = 2.5, so the boundary x₂ = 2.5 sits exactly in the middle with margin = (4 − 1)/2 = 1.5.w = (0, 1) (we only care about x₂) and bias b = −2.5. Check: for B, label · (w·x + b) = +1 · (1 − 2.5) = −1.5 ❌ — the sign is wrong, so let's flip the convention to w = (0, −1), b = +2.5. Now for B: +1 · (−1 + 2.5) = +1.5 ✓. For C: −1 · (−4 + 2.5) = +1.5 ✓.w = (0, −1), b = +2.5 is not yet in SVM's canonical scaling. The scale of (w, b) is arbitrary: multiplying both by any positive constant describes the same boundary. SVM pins it down by requiring the closest points to evaluate to exactly 1. Divide through by 1.5:w = (0, −2/3), b = 5/3. Now B gives +1 · (−2/3 + 5/3) = +1 and C gives −1 · (−8/3 + 5/3) = +1 — the constraints are now tight, which is the precise statement of "these are the support vectors."Confirm the support-vector property: remove A and retrain → same boundary. Remove B → boundary shifts. That's the whole idea in a dozen lines of arithmetic.
#Soft Margin SVM: Handling Non-Separable Data
- Large C (e.g., 100): Few violations allowed. Narrow margin. Risk of overfitting.
- Small C (e.g., 0.01): Many violations allowed. Wide margin. Risk of underfitting.
- C is analogous to the inverse of regularization strength in logistic regression.
Why is the slack penalty the same thing as the hinge loss that appears later in this lesson? Open the derivation to see that each slack variable is forced to equal it.
#From Primal to Dual: Why Support Vectors Are the Only Thing That Matters
(w, b). That formulation is correct, but it hides the headline property of the algorithm — that the solution depends on a handful of points, not on w directly. To see why support vectors fall out of the math (and to unlock the kernel trick in the next section), we need to convert the primal problem into its Lagrangian dual. The journey is four lines of calculus and one substitution, but it is the single most important derivation in classical ML.The Lagrangian, the KKT conditions and the dual of the SVM are derived in Convex Optimization, KKT & Lagrangian Duality. The five steps below do not repeat that general theory; they apply it to the SVM and read off what it says about support vectors and kernels.
#Step 1: Write the Lagrangian
½||w||² subject to y_i(w·x_i + b) ≥ 1 for every i. Introduce one Lagrange multiplier α_i ≥ 0 per constraint and form the Lagrangian:#Step 2: Take Derivatives: KKT Stationarity
L over the primal variables (w, b). Setting partial derivatives to zero gives two clean identities:w lives entirely in the subspace spanned by the training points. There is no w independent of the data — every degree of freedom of the model is carried by the α_i.#Step 3: Substitute Back: The Dual Problem
w* = Σ α_i y_i x_i and Σ α_i y_i = 0 back into L. After cancellation, the variable b drops out (it was multiplied by a zero sum), w disappears (it was rewritten in terms of α), and the entire optimization reduces to:x_i · x_j in the objective.#Step 4: Complementary Slackness: The Support Vectors Fall Out
#Step 5: Why This Exposes the Kernel Trick
x_i · x_j. The algorithm never asks for x_i directly — only for "how similar is point i to point j?". This is the structural opening for the kernel trick: replace every x_i · x_j with a kernel function K(x_i, x_j) that also computes an inner product, but in some implicit (possibly infinite-dimensional) feature space φ(x). The optimizer never knows or cares what φ looks like. It only ever sees the kernel values. The next section unpacks this fully, but you already have the machinery: anywhere you see x_i · x_j in the dual, you can swap in K(x_i, x_j) and the SVM seamlessly learns a non-linear boundary in the original input space.#The Kernel Trick: Non-Linear Boundaries
What if the classes cannot be separated by any straight line? The kernel trick maps data to a higher-dimensional space where a linear boundary exists.
Now watch the lifting happen visually — drag points in 2D and see how the kernel feature map lifts them into a third dimension where a flat plane can separate them.
Why does swapping x_i . x_j for K(x_i, x_j) change nothing else in the algorithm? Open the derivation to see that both training and prediction use the data only through inner products.
#Common Kernels
Is the polynomial kernel really an inner product in a bigger space? Open the derivation to build that space by hand for two inputs and degree 2.
The claim that the RBF kernel lives in an infinite-dimensional space can be shown with one series. Open the derivation to see it.
Run real sklearn SVMs with three different kernels on the moons dataset, a classic non-linearly-separable problem, and see how the kernel choice changes the decision boundary and accuracy.
On the moons dataset above, the linear kernel scored noticeably lower than RBF. Why?
#The RBF Kernel's Two Hyperparameters
- C (regularization): Controls the tradeoff between margin width and misclassification
- gamma (kernel width): Controls how far the influence of a single training point reaches
- Small gamma: smooth decision boundary (underfitting risk)
- Large gamma: wiggly boundary that closely follows the data (overfitting risk)
You must tune C and gamma together (typically via grid search with cross-validation). They interact: high C + high gamma = extremely complex boundary (overfitting). Low C + low gamma = smooth, simple boundary (underfitting).
#SVM vs. Logistic Regression
| Aspect | SVM | Logistic Regression |
|---|---|---|
| Decision boundary | Maximum margin | Maximum likelihood |
| Output | Distance from boundary | Calibrated probability |
| Loss function | Hinge loss | Log loss |
| Regularization | C (inverse) | 1/C |
| Non-linear boundaries | Kernel trick | Polynomial features |
| Best for | Small-to-medium data, clear margins | Large data, probability estimation |
#Try It Yourself
Tests: Verify that margin width decreases as C increases. Verify that the number of support vectors decreases as C increases. Find the C value that gives the best test accuracy.
#When to Use SVMs vs. Alternatives
| Situation | Reach for | Why |
|---|---|---|
| Small-to-medium dataset (< 10K rows), clear class margins | SVM with RBF kernel | Maximum margin = best generalization on small data |
| Many features, few samples (d ≫ n: genomics, bioinformatics) | Linear SVM (LinearSVC) | Data is usually already linearly separable in high-dim space |
| Text classification with TF-IDF | Linear SVM | Long the standard before transformers; still very competitive |
| Tabular data, 100K+ rows, complex interactions | Gradient Boosting (LightGBM/XGBoost) | SVM scales poorly past 100K and rarely beats GBM on tabular |
| Images, audio, raw text | Neural networks | Learned features beat hand-crafted kernels |
| Anomaly detection (only one class is "normal") | One-Class SVM | Specialized SVM variant for outlier detection |
| You need calibrated probability outputs | Logistic regression (or SVC(probability=True) + Platt scaling) | Raw SVM outputs are distances, not probabilities |
#Key Takeaways
- SVMs find the widest margin between classes. The decision boundary is placed to maximize the gap between the nearest points of each class, leading to better generalization on unseen data
- Only support vectors determine the boundary. Removing any non-support-vector training point does not change the decision boundary at all; this makes SVMs robust and memory-efficient
- The kernel trick enables non-linear boundaries. By implicitly mapping data to higher dimensions (via RBF, polynomial, or other kernels), SVMs create complex decision boundaries without explicitly computing the transformation
- SVMs work best on small-to-medium, well-structured data. For large datasets or high-dimensional unstructured data, tree-based methods or neural networks typically outperform SVMs in both speed and accuracy
#Quick Check
What are support vectors?