v9.1.0
Menu

Chapter 7: Support Vector Machines

Week 13-14

Master Support Vector Machines, one of the most elegant algorithms in machine learning. Learn how SVMs find optimal separating hyperplanes with maximum margin, handle non-separable data with soft margins, and tackle non-linear problems through the powerful kernel trick.

Topics
5
Demos
4
Min read
52

Chapter Overview

Support Vector Machines represent a beautiful intersection of geometry, optimization, and learning theory. The core idea is elegantly simple: among all hyperplanes that separate two classes, choose the one with the maximum margin to the nearest training points.

This maximum margin principle has deep theoretical justification—it maximizes the geometric separation between classes, leading to better generalization. The points that lie exactly on the margin boundaries are called support vectors, and remarkably, only these points determine the decision boundary.

Real-world data is rarely perfectly separable, so soft margin SVMs allow some violations by introducing slack variables. The regularization parameter C controls the trade-off: high C penalizes misclassifications heavily (narrow margin, potential overfitting), while low C allows more errors (wide margin, potential underfitting).

The true power of SVMs comes from the kernel trick, which enables learning non-linear decision boundaries without explicitly computing high-dimensional feature mappings. By using kernel functions that compute inner products in transformed spaces, SVMs can learn complex patterns while remaining computationally tractable.

This chapter covers:

  • Maximum Margin: The geometric intuition behind finding the optimal separating hyperplane
  • Soft Margin: Handling overlapping classes with slack variables and the C parameter
  • Kernel Trick: Using RBF, polynomial, and other kernels to learn non-linear boundaries
  • Practical SVM: Feature scaling, hyperparameter tuning, and when to use SVMs
  • SVR: Adapting the SVM framework for regression with ε-insensitive loss

Chapter Roadmap

Click any topic to jump in

Interactive demo
1
Maximum Margin

The geometric insight — find the separating hyperplane with the widest gap to nearest points.

HyperplaneFunctional MarginGeometric MarginSupport VectorsHard Margin SVMWhy Maximum Margin?
Relaxing perfect separation and adding non-linearity

Two extensions that make SVMs practical

2
Soft Margin SVM

Handle overlapping classes with slack variables and the C parameter for real-world data.

Slack VariablesSoft Margin ObjectiveC ParameterHinge Loss
3
Kernel Trick

Learn non-linear boundaries by computing inner products in high-dimensional spaces implicitly.

Kernel FunctionWhy Kernels WorkLinear KernelPolynomial KernelRBF (Gaussian) KernelGamma Parameter (RBF)Sigmoid Kernel
Applying SVMs in practice

Classification pipelines and regression adaptation

4
Practical SVM

Feature scaling, hyperparameter tuning, multi-class strategies, and when to choose SVMs.

Feature Scaling is CriticalC and Gamma InteractionGrid Search StrategyWhen to Use SVMSVM ComplexityProbability OutputsMulti-class Strategy
5
Support Vector Regression

Adapt the SVM margin framework to regression with the epsilon-insensitive loss tube.

ε-Insensitive LossSVR Objectiveε ParameterSVR Kernels

Topics

5 topics in this chapter

The previous chapter, Ensemble Methods, built strong classifiers by averaging many trees. Now we return to a single linear boundary and ask a sharper question. When two classes can be separated by a straight line, infinitely many lines do it perfectly on the training set. Logistic regression picks one by maximizing likelihood, and the perceptron stops at whichever separating line it reaches first. Which of these lines should we trust on new data? A line that grazes a training point will misclassify a test point that lands slightly to the wrong side of it.

Support Vector Machines answer with a geometric principle: choose the boundary that stays as far as possible from the nearest training points of both classes. This topic builds that idea step by step. We define a hyperplane, then two ways to measure a point's distance from it, the functional and geometric margins, and see why only the second is meaningful. We then meet the support vectors, the few points that pin the boundary, write the hard-margin optimization problem, and close with why a wide margin generalizes better.

Definition

A linear support vector machine classifies with the sign of wTx+b\mathbf{w}^T\mathbf{x} + b. Among all hyperplanes that separate the training data, the hard-margin SVM chooses the one that maximizes the margin, the distance 2/∥w∥2/\lVert\mathbf{w}\rVert between the two parallel boundaries wTx+b=±1\mathbf{w}^T\mathbf{x} + b = \pm 1, subject to every point lying on its correct side.

In this topic

  1. 1Hyperplane
  2. 2Functional Margin
  3. 3Geometric Margin
  4. 4Support Vectors
  5. 5Hard Margin SVM
  6. 6Why Maximum Margin?
1 of 6
Hyperplane

wTx+b=0\mathbf{w}^T \mathbf{x} + b = 0

A hyperplane is the set of points x\mathbf{x} with wTx+b=0\mathbf{w}^T\mathbf{x} + b = 0: a line in 2D, a plane in 3D, and a flat (d−1)(d-1)-dimensional surface in dd dimensions. The weight vector w\mathbf{w} is normal (perpendicular) to it and sets its orientation; the bias bb shifts it away from the origin. The classifier predicts +1+1 when wTx+b>0\mathbf{w}^T\mathbf{x} + b > 0 and −1-1 otherwise. The signed distance of a point from the hyperplane is (wTx+b)/∥w∥(\mathbf{w}^T\mathbf{x} + b)/\lVert\mathbf{w}\rVert. This is the same linear score used by logistic regression in the Classification chapter; SVMs differ only in how they choose w\mathbf{w} and bb.

Mathematical Intuition

The hyperplane wTx+b=0\mathbf{w}^T\mathbf{x} + b = 0 partitions Rn\mathbb{R}^n into two half-spaces. The normal vector w\mathbf{w} is perpendicular to the hyperplane, and b/∣∣w∣∣b/||\mathbf{w}|| is the signed distance from the origin. The sign of wTx+b\mathbf{w}^T\mathbf{x} + b determines which side of the hyperplane a point falls on. In 2D this is a line, in 3D a plane, and in nnD a (n−1)(n-1)-dimensional affine subspace — the geometry is the same regardless of dimensionality.

Example:

w=[2,1], b=-3. Is point (2,1) on positive or negative side?

2 of 6
Functional Margin

γ^i=yi(wTxi+b)\hat{\gamma}_i = y_i(\mathbf{w}^T\mathbf{x}_i + b)

The functional margin of training point ii is γ^i=yi(wTxi+b)\hat{\gamma}_i = y_i(\mathbf{w}^T\mathbf{x}_i + b), where the label yiy_i is +1+1 or −1-1. Multiplying by the label makes it positive exactly when the point is classified correctly, and larger values suggest more confidence. Its flaw is scale: replacing (w,b)(\mathbf{w}, b) with (cw,cb)(c\mathbf{w}, cb) for any c>0c > 0 describes the same hyperplane but multiplies every functional margin by cc. Maximizing it directly is therefore meaningless, since doubling w\mathbf{w} always wins. SVMs fix this by normalizing, either dividing by ∥w∥\lVert\mathbf{w}\rVert or requiring the closest points to have functional margin exactly 1.

Mathematical Intuition

The functional margin γ^i=yi(wTxi+b)\hat{\gamma}_i = y_i(\mathbf{w}^T\mathbf{x}_i + b) is positive when the point is correctly classified and its magnitude reflects confidence. However, replacing (w,b)(\mathbf{w}, b) with (2w,2b)(2\mathbf{w}, 2b) doubles the functional margin without changing the hyperplane — the margin is not scale-invariant. This is why we need to normalize by ∣∣w∣∣||\mathbf{w}|| to get a geometrically meaningful quantity, or equivalently constrain the optimization so that min⁡i∣wTxi+b∣=1\min_i |\mathbf{w}^T\mathbf{x}_i + b| = 1.

Example:

y=+1, wᵀx+b=5. Functional margin? If we double w and b?

3 of 6
Geometric Margin

γ=2∣∣w∣∣\gamma = \frac{2}{||\mathbf{w}||}

The geometric margin is a true distance, unaffected by rescaling w\mathbf{w} and bb. SVMs fix the scale by requiring yi(wTxi+b)≥1y_i(\mathbf{w}^T\mathbf{x}_i + b) \geq 1 for all points, with equality for the closest ones. Those points then sit on the parallel planes wTx+b=±1\mathbf{w}^T\mathbf{x} + b = \pm 1, each at distance 1/∥w∥1/\lVert\mathbf{w}\rVert from the decision boundary, so the full width of the empty band between the classes is γ=2/∥w∥\gamma = 2/\lVert\mathbf{w}\rVert, the formula above. A wider margin requires a smaller ∥w∥\lVert\mathbf{w}\rVert. This turns the geometric goal, a widest band, into an algebraic one: minimize the norm of the weights.

Mathematical Intuition

The geometric margin γ=2/∣∣w∣∣\gamma = 2/||\mathbf{w}|| is the perpendicular distance between the two margin boundaries wTx+b=±1\mathbf{w}^T\mathbf{x} + b = \pm 1. Maximizing 2/∣∣w∣∣2/||\mathbf{w}|| is equivalent to minimizing ∣∣w∣∣2/2||\mathbf{w}||^2/2, transforming a geometric problem into a convex quadratic program. The factor of 1/21/2 is a convention that simplifies the gradient to w\mathbf{w} instead of 2w2\mathbf{w}. Larger margins correspond to smoother decision boundaries with better generalization — this is formalized by VC dimension theory.

Example:

||w|| = 2. What's the margin width?

4 of 6
Support Vectors

Support vectors are the training points that lie exactly on the margin planes, where yi(wTxi+b)=1y_i(\mathbf{w}^T\mathbf{x}_i + b) = 1. In the dual form of the optimization, each point gets a weight αi≥0\alpha_i \geq 0 and the solution is w=∑iαiyixi\mathbf{w} = \sum_i \alpha_i y_i \mathbf{x}_i. Points strictly outside the margin get αi=0\alpha_i = 0, so only support vectors shape the boundary. Delete any other point, retrain, and the hyperplane is unchanged. This sparsity is what makes SVMs distinctive: logistic regression gives every point some influence. The flip side is sensitivity: move or mislabel a single support vector and the whole boundary shifts.

Mathematical Intuition

Support vectors are the training points where the constraint yi(wTxi+b)≥1y_i(\mathbf{w}^T\mathbf{x}_i + b) \geq 1 is active (equality holds). By the KKT complementarity conditions, non-support vectors have dual variables αi=0\alpha_i = 0 and contribute nothing to w=∑iαiyixi\mathbf{w} = \sum_i \alpha_i y_i \mathbf{x}_i. This sparsity means the solution depends only on the hardest-to-classify points. Removing any non-support vector does not change the optimal hyperplane — the SVM is effectively determined by a small subset of the data.

Example:

1000 training points. SVM has 15 support vectors. How many points actually matter?

5 of 6
Hard Margin SVM

min⁡12∣∣w∣∣2\min \frac{1}{2}||\mathbf{w}||^2 s.t. yi(wTxi+b)≥1y_i(\mathbf{w}^T\mathbf{x}_i + b) \geq 1

The hard-margin SVM combines the previous concepts into one problem: minimize 12∥w∥2\frac{1}{2}\lVert\mathbf{w}\rVert^2 subject to yi(wTxi+b)≥1y_i(\mathbf{w}^T\mathbf{x}_i + b) \geq 1 for every training point. The objective is a convex quadratic and the constraints are linear, so this is a quadratic program with a single global optimum and no local minima. The squared norm is minimized instead of maximizing 2/∥w∥2/\lVert\mathbf{w}\rVert because it is smooth and convex; the factor 12\frac{1}{2} just tidies the gradient. Its fatal weakness is the requirement of perfect separability: one overlapping or mislabeled point makes the constraints impossible to satisfy, and an outlier near the boundary can drastically narrow the margin.

Mathematical Intuition

The hard margin optimization min⁡12∣∣w∣∣2\min \frac{1}{2}||\mathbf{w}||^2 s.t. yi(wTxi+b)≥1y_i(\mathbf{w}^T\mathbf{x}_i + b) \geq 1 is a convex quadratic program with linear constraints. Strong duality holds (Slater's condition), so the dual max⁡∑iαi−12∑i,jαiαjyiyjxiTxj\max \sum_i \alpha_i - \frac{1}{2}\sum_{i,j} \alpha_i \alpha_j y_i y_j \mathbf{x}_i^T\mathbf{x}_j gives the same solution. The dual depends only on inner products xiTxj\mathbf{x}_i^T\mathbf{x}_j — this is the foundation for the kernel trick.

Example:

Data has one mislabeled point making classes overlap. Hard margin SVM?

6 of 6
Why Maximum Margin?

Why should the widest band generalize best? Intuitively, test points are perturbed versions of training points. If every training point is at least half the margin width from the boundary, small perturbations cannot push them across. Formally, statistical learning theory bounds the capacity of large-margin classifiers: for data inside a ball of radius RR, the VC dimension of hyperplanes with margin γ\gamma is bounded by roughly R2/γ2R^2/\gamma^2, regardless of the number of features. A wide margin therefore limits complexity even in very high dimensions, which is why SVMs work well on text. The bound depends on scale, so it presumes the features are standardized.

Mathematical Intuition

VC theory gives the formal justification. With probability 1−δ1 - \delta, test error is at most training error plus a term of order (dVClog⁡n+log⁡(1/δ))/n\sqrt{(d_{\text{VC}} \log n + \log(1/\delta))/n}. For hyperplanes that separate data lying in a ball of radius RR with distance at least ρ\rho from every point to the boundary, dVC≤min⁡(⌈R2/ρ2⌉,d)+1d_{\text{VC}} \leq \min(\lceil R^2/\rho^2 \rceil, d) + 1, which does not grow with the ambient dimension dd once R2/ρ2R^2/\rho^2 is the smaller term. Maximizing the margin shrinks this capacity term, which explains why maximum-margin classifiers can generalize in very high-dimensional spaces, provided features are scaled so that RR is meaningful.

Example:

Margin A: 0.1 units. Margin B: 2 units. New point is 0.5 units from boundary. Which classifies correctly?

Theory Exercise

Problem:

In a trained SVM, you have 3 support vectors out of 100 training points. What happens to the decision boundary if you remove a non-support-vector point?

Hints:
  • What determines the decision boundary?
  • Are all training points equally important?
  • Think about the optimization solution

Coding Exercise

Problem:

Train a hard(ish)-margin linear SVM on a linearly separable 2D dataset, then inspect which training points became support vectors. Confirm that only the support vectors define the boundary by checking how few there are relative to the dataset.

Hints:
  • Use sklearn.svm.SVC(kernel='linear', C=1e6) to approximate a hard margin
  • After fitting, clf.support_vectors_ holds the support vectors and clf.support_ holds their indices
  • clf.coef_ and clf.intercept_ give w and b of the hyperplane

Related Problems on PixelBank