◆ AI All-in-One

Level 3 In-Depth AI · Classical Machine Learning

Support Vector Machines

A classifier that draws the boundary with the widest possible safety gap between the classes. With the kernel trick it can draw curved boundaries too, without ever computing the curved features.

Level
●●●●● Intermediate
Reading
14 min
To learn it well
1 hour to read, an afternoon to practise
↗ Plan a path here

Read first

Logistic RegressionDot Product, Norms and Similarity

This leads to

—
The full path from zero — 12 concepts before this one
  1. What Is AI?
  2. Derivatives and Slopes
  3. Vectors
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Dot Product, Norms and Similarity
  8. Supervised, Unsupervised and Reinforcement Learning
  9. Gradient Descent
  10. Supervised Learning
  11. Linear Regression
  12. Logistic Regression
  13. Support Vector Machines

Read them roughly in this order. See it on the concept map →

Why it matters

From the mid-1990s to about 2012, the support vector machine (SVM) was the most respected general-purpose classifier in machine learning. It recognised handwritten digits, classified text, detected faces and identified proteins. It came with an elegant mathematical theory and a guarantee that training finds the single best solution, with no local minima to get stuck in.

Deep learning has since taken over images, audio and text, and gradient-boosted trees dominate tables. But SVMs are still worth learning, and still used:

  • On small and medium datasets with many features (a few hundred to tens of thousands of examples), an SVM is often among the most accurate models available.
  • The idea of the margin, leaving a safety gap around the decision boundary, runs through modern ML theory.
  • The kernel trick is one of the most beautiful ideas in the field: it lets a linear method draw curved boundaries by computing only dot products. Kernels reappear in Gaussian processes, in the analysis of Attention, and in theories of how wide neural networks learn.
  • The hinge loss that SVMs optimise is one of the standard Loss Functions.

The intuition

Picture two groups of houses on a map, red-roofed on one side and blue-roofed on the other, and you must build a straight road between them. Many roads would separate the two groups. Which is best?

Most people choose the road that stays as far as possible from the nearest house on either side. A road that scrapes past a house leaves no room for error: a new house built slightly off the pattern would end up on the wrong side. A road through the middle of the widest gap is the safest bet for houses not yet built.

That is the SVM idea. Among all straight boundaries that separate the classes, pick the one with the widest margin, the empty band between the boundary and the nearest points of each class.

decision boundary w·x + b = 0 here x₁ + x₂ = 2.5 margin edges (dashed) w·x + b = ±1 margin width = 2 / ‖w‖ = 2.12 for this data support vectors (ringed) the three points touching the margin; only they fix the boundary red dotted: also separates the classes, but passes close to the points class −1 class +1
Fig. 1 A maximum-margin classifier. The solid line separates the two classes with the widest possible empty band (shaded) around it. Only the three ringed points, the support vectors, touch the edges of the band. Moving any other point (without crossing the band) would not change the boundary. The red dotted line also separates the classes but passes close to the points.

Notice which points matter. The boundary is held in place entirely by the few points sitting on the edge of the margin. These are the support vectors: they "support" the boundary like posts holding up a fence. You could delete every other training point and get exactly the same answer. That is where the method gets its name.

Key idea An SVM picks the separating boundary with the widest margin to the nearest points. Those nearest points, the support vectors, are the only ones that determine it. The kernel trick extends this to curved boundaries by replacing every dot product with a similarity function.

How it works

The linear classifier

Like Logistic Regression and the The Perceptron, a linear SVM scores an input x\mathbf{x} with a weighted sum:

f(x)=w⋅x+bf(\mathbf{x}) = \mathbf{w} \cdot \mathbf{x} + b

Here w\mathbf{w} is the weight vector, bb the bias, and w⋅x\mathbf{w} \cdot \mathbf{x} the dot product. It predicts class +1+1 if f(x)>0f(\mathbf{x}) > 0 and class −1-1 if f(x)<0f(\mathbf{x}) < 0. SVMs label the classes −1-1 and +1+1 rather than 0 and 1, which makes the formulas tidier. The boundary is the line (or plane, or hyperplane in many dimensions) where f(x)=0f(\mathbf{x}) = 0. The vector w\mathbf{w} points at right angles to it.

Measuring the margin

The SVM fixes the scale of w\mathbf{w} and bb so that the closest points on each side have f(x)=+1f(\mathbf{x}) = +1 or −1-1 exactly. The margin edges are then the lines w⋅x+b=±1\mathbf{w} \cdot \mathbf{x} + b = \pm 1, and the distance between them works out to:

margin width=2∥w∥\text{margin width} = \frac{2}{\lVert \mathbf{w} \rVert}

where ∥w∥\lVert \mathbf{w} \rVert is the length of w\mathbf{w}. A wider margin means a shorter w\mathbf{w}. So "maximise the margin" becomes "make ∥w∥\lVert \mathbf{w} \rVert as small as possible, while classifying every point correctly with a score of at least 1":

min⁡w,b  12∥w∥2subject toyi(w⋅xi+b)≥1 for every i\min_{\mathbf{w}, b} \; \tfrac{1}{2}\lVert \mathbf{w} \rVert^2 \quad \text{subject to} \quad y_i(\mathbf{w} \cdot \mathbf{x}_i + b) \ge 1 \text{ for every } i

Here yiy_i is the label (±1\pm 1) of example ii. The product yif(xi)y_i f(\mathbf{x}_i) is positive when the example is on the correct side, and at least 1 when it is also outside the margin. This is a convex problem, a single bowl with one bottom, so there is exactly one best answer and standard solvers find it.

A worked example by hand

Take the six innermost points from the figure. Class −1-1: (0,0)(0,0), (1,0)(1,0), (0,1)(0,1). Class +1+1: (2,2)(2,2), (3,2)(3,2), (2,3)(2,3).

By symmetry the best boundary runs at 45°, so w=(a,a)\mathbf{w} = (a, a) for some aa. The closest negative points, (1,0)(1,0) and (0,1)(0,1), both have x1+x2=1x_1 + x_2 = 1; the closest positive point, (2,2)(2,2), has x1+x2=4x_1 + x_2 = 4. These are the support vectors, and they must score exactly −1-1 and +1+1:

  • a⋅1+b=−1a \cdot 1 + b = -1
  • a⋅4+b=+1a \cdot 4 + b = +1

Subtracting gives 3a=23a = 2, so a=2/3a = 2/3, and then b=−1−2/3=−5/3b = -1 - 2/3 = -5/3. The classifier is:

f(x)=23x1+23x2−53f(\mathbf{x}) = \tfrac{2}{3} x_1 + \tfrac{2}{3} x_2 - \tfrac{5}{3}

The boundary f=0f = 0 is the line x1+x2=2.5x_1 + x_2 = 2.5, exactly midway. The margin is 2/∥w∥=2/(232)=3/2≈2.122 / \lVert \mathbf{w} \rVert = 2 / (\tfrac{2}{3}\sqrt{2}) = 3/\sqrt{2} \approx 2.12. Scikit-learn's SVC(kernel="linear") gives w=(0.667,0.667)\mathbf{w} = (0.667, 0.667) and b=−1.667b = -1.667 on this data, matching.

Classify a new point (2,1)(2, 1): f=23(3)−53=13>0f = \tfrac{2}{3}(3) - \tfrac{5}{3} = \tfrac{1}{3} > 0, so class +1+1. But ff is less than 1, which tells you the point falls inside the margin: a less confident call.

Soft margins: allowing mistakes

Real data is rarely perfectly separable. One mislabelled point on the wrong side would make the problem above impossible, and a single outlier near the boundary can drag it badly. The fix is the soft margin: allow points to violate the margin, but charge a penalty for each violation.

The penalty is the hinge loss:

ℓ(xi,yi)=max⁡(0,  1−yif(xi))\ell(\mathbf{x}_i, y_i) = \max\big(0, \; 1 - y_i f(\mathbf{x}_i)\big)

It is zero for points correctly classified and outside the margin (yif≥1y_i f \ge 1), and grows linearly as a point moves into the margin and across to the wrong side. Unlike the log loss of Logistic Regression, it is exactly zero for comfortably correct points. That is why most points end up with no influence on the solution, and only the support vectors matter.

The full soft-margin SVM balances a wide margin against the total hinge loss:

min⁡w,b  12∥w∥2+C∑i=1Nmax⁡(0,1−yi(w⋅xi+b))\min_{\mathbf{w}, b} \; \tfrac{1}{2}\lVert \mathbf{w} \rVert^2 + C \sum_{i=1}^{N} \max\big(0, 1 - y_i(\mathbf{w} \cdot \mathbf{x}_i + b)\big)

The hyperparameter CC sets the trade-off:

  • Large CC: violations are expensive. The SVM bends over backwards to classify every training point, giving a narrow margin and a risk of Overfitting and the Bias–Variance Tradeoff.
  • Small CC: violations are cheap. The margin is wide and tolerant of outliers, at the risk of underfitting.

The 12∥w∥2\tfrac{1}{2}\lVert \mathbf{w} \rVert^2 term is just L2 Regularization: L1 and L2 in disguise. A linear SVM is "hinge loss plus L2 penalty", where logistic regression is "log loss plus L2 penalty". In practice the two often perform very similarly.

The kernel trick

A straight line can't separate data where one class surrounds the other. The classic remedy is to add features. In the one-dimensional example below, blue points sit in the middle and orange points on both sides. No single threshold on xx separates them. But add a second feature x2x^2, and the orange points rise high while the blue points stay low, so a flat line separates them.

-3 0 3 x 1 feature: not separable no single threshold on x splits blue (middle) from orange (outside) φ(x) = (x, x²) x² x x² = 2.5 2 features: a straight line separates them a linear boundary in the lifted space is a curved one (|x| = 1.58) in the original
Fig. 2 The idea behind kernels. On the left, one feature: blue points in the middle and orange points on the outside cannot be split by any threshold. On the right, each point is lifted to (x, x²). Now a straight line separates them. That straight line corresponds to a curved rule, |x| > 1.58, in the original space.

A feature map ϕ\phi turns each input into a longer vector of new features. With many inputs and high-degree combinations, though, the new vectors become enormous. All the products of up to 3 features out of 1,000 already number more than 160 million.

Here is the trick. When the SVM problem is rewritten in its "dual" form, the data only ever appears inside dot products between pairs of examples, ϕ(xi)⋅ϕ(xj)\phi(\mathbf{x}_i) \cdot \phi(\mathbf{x}_j). And for many useful feature maps, that dot product can be computed directly from the original vectors, cheaply, without ever building ϕ\phi. A function that does this is called a kernel:

K(a,b)=ϕ(a)⋅ϕ(b)K(\mathbf{a}, \mathbf{b}) = \phi(\mathbf{a}) \cdot \phi(\mathbf{b})

A worked example. For 2D inputs, let ϕ(x)=(x12,2 x1x2,x22)\phi(\mathbf{x}) = (x_1^2, \sqrt{2}\,x_1 x_2, x_2^2). Take a=(1,2)\mathbf{a} = (1, 2) and b=(3,1)\mathbf{b} = (3, 1).

  • The long way: ϕ(a)=(1,22,4)\phi(\mathbf{a}) = (1, 2\sqrt{2}, 4) and ϕ(b)=(9,32,1)\phi(\mathbf{b}) = (9, 3\sqrt{2}, 1). Their dot product is 9+12+4=259 + 12 + 4 = 25.
  • The short way: (a⋅b)2=(1⋅3+2⋅1)2=52=25(\mathbf{a} \cdot \mathbf{b})^2 = (1 \cdot 3 + 2 \cdot 1)^2 = 5^2 = 25.

Same answer, without computing the three new features. For higher degrees and dimensions the savings are huge. The final classifier becomes a weighted sum over support vectors:

f(x)=∑i∈SVαi yi K(xi,x)+bf(\mathbf{x}) = \sum_{i \in \text{SV}} \alpha_i \, y_i \, K(\mathbf{x}_i, \mathbf{x}) + b

Each weight αi\alpha_i is learned and is non-zero only for support vectors. Read it as: compare the new point with each support vector using the kernel, and add up their votes. It is a smarter cousin of k-Nearest Neighbours.

Common kernels

  • Linear: K(a,b)=a⋅bK(\mathbf{a}, \mathbf{b}) = \mathbf{a} \cdot \mathbf{b}. No curves. Best when there are already many features, as in text.
  • Polynomial: K(a,b)=(γ a⋅b+r)dK(\mathbf{a}, \mathbf{b}) = (\gamma\, \mathbf{a} \cdot \mathbf{b} + r)^d. Includes all feature products up to degree dd.
  • RBF (radial basis function, or Gaussian): K(a,b)=exp⁡(−γ∥a−b∥2)K(\mathbf{a}, \mathbf{b}) = \exp(-\gamma \lVert \mathbf{a} - \mathbf{b} \rVert^2). Similarity decays with distance: 1 for identical points, near 0 for far-apart ones. Its implicit feature space is infinite-dimensional, yet each kernel value is one cheap formula. It is the default choice.

For the RBF kernel, γ\gamma ("gamma") sets how far each support vector's influence reaches. Small γ\gamma means wide influence and smooth boundaries; large γ\gamma means each point only affects its immediate neighbourhood, giving wiggly boundaries that can wrap around individual points.

γ = 0.02: too smooth training accuracy 76% 400 support vectors γ = 1: about right training accuracy 97% 91 support vectors γ = 50: too wiggly training accuracy 99% 338 support vectors
Fig. 3 An RBF-kernel SVM on two noisy rings, with three values of gamma. Too small, and the boundary is too smooth to follow the inner ring. Too large, and it wraps around individual points, reaching 99% training accuracy by memorising noise. In between, it finds the circle.

CC and γ\gamma interact, so tune them together on a grid spaced by factors of 10, using Cross-Validation.

In code

A linear soft-margin SVM from scratch, trained by (sub)gradient descent on the hinge-loss objective. The hinge has a kink at 1, so we use a subgradient: points with margin below 1 push on w\mathbf{w}, the rest don't.

import numpy as np
from sklearn.datasets import make_blobs
from sklearn.svm import SVC

X, y01 = make_blobs(n_samples=200, centers=2, cluster_std=1.0, random_state=4)
y = np.where(y01 == 1, 1, -1)                 # SVMs use labels -1 and +1
X = (X - X.mean(0)) / X.std(0)                # scale features

C, lr, n = 100.0, 0.01, len(y)
w, b = np.zeros(2), 0.0
for epoch in range(5000):
    margins = y * (X @ w + b)
    viol = margins < 1                         # points inside the margin or misclassified
    # subgradient of  0.5*||w||^2 + C * mean(hinge)
    grad_w = w - C * (y[viol, None] * X[viol]).sum(0) / n
    grad_b = -C * y[viol].sum() / n
    w -= lr * grad_w
    b -= lr * grad_b

print("from scratch: w =", w.round(3), " b =", round(b, 3),
      " accuracy =", (np.sign(X @ w + b) == y).mean())

svc = SVC(kernel="linear", C=C / n).fit(X, y)  # same objective, scaled the way sklearn defines C
print("scikit-learn: w =", svc.coef_[0].round(3), " b =", svc.intercept_.round(3)[0],
      " support vectors:", len(svc.support_))

# from scratch: w = [0.207 2.454]  b = 0.17  accuracy = 0.965
# scikit-learn: w = [0.202 2.44 ]  b = 0.168  support vectors: 33

The two agree closely, and only 33 of the 200 points end up as support vectors. Now kernels in scikit-learn, on two noisy concentric rings that no straight line can separate:

from sklearn.datasets import make_circles
from sklearn.model_selection import GridSearchCV, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

X, y = make_circles(n_samples=400, noise=0.15, factor=0.5, random_state=0)   # one ring inside another

for kernel in ("linear", "poly", "rbf"):
    model = make_pipeline(StandardScaler(), SVC(kernel=kernel, degree=2))
    print(f"{kernel:6}  accuracy {cross_val_score(model, X, y, cv=5).mean():.3f}")

grid = GridSearchCV(make_pipeline(StandardScaler(), SVC(kernel="rbf")),
                    {"svc__C": [0.1, 1, 10, 100], "svc__gamma": [0.01, 0.1, 1, 10]}, cv=5)
grid.fit(X, y)
print("best:", grid.best_params_, " accuracy", round(grid.best_score_, 3))

# linear  accuracy 0.495
# poly    accuracy 0.960
# rbf     accuracy 0.963
# best: {'svc__C': 0.1, 'svc__gamma': 1}  accuracy 0.965

The linear SVM is no better than a coin flip, while degree-2 polynomial and RBF kernels both find the circle. SVC doesn't output probabilities by default; pass probability=True (slower, uses internal cross-validation) or use decision_function for scores. For large datasets with many features, LinearSVC is far faster than SVC(kernel="linear"). For regression, SVR uses the same ideas with an "ε-insensitive" loss that ignores errors smaller than ε.

Common pitfalls

  • Not scaling features. Both the margin and the RBF kernel depend on distances, so a feature in large units dominates. Always standardise first, inside a pipeline.
  • Kernel SVMs on big data. Training a kernel SVM needs to compare many pairs of examples. Its cost grows somewhere between N2N^2 and N3N^3, so beyond roughly 100,000 examples it becomes very slow. Use LinearSVC, approximate kernels, or switch to Gradient Boosting: XGBoost and LightGBM or a neural network.
  • Tuning only one of CC and γ\gamma. They trade off against each other. Search them together on a log-spaced grid.
  • Treating the score as a probability. f(x)f(\mathbf{x}) is a distance-like score, not a probability. Use calibration (Platt scaling, which is what probability=True does) if you need probabilities.
  • Imbalanced classes. With 99% of one class, the SVM may ignore the rare class. Use class_weight="balanced".

Watch out An RBF SVM with unscaled features or a badly chosen γ\gamma can silently produce a model that predicts one class for everything, or memorises the training set. Scale, then grid-search CC and γ\gamma with cross-validation, every time.

Where it leads

  • Logistic regression is the closest relative: swap hinge loss for log loss and you get calibrated probabilities with similar boundaries. See Logistic Regression.
  • Neural networks learn their feature map ϕ\phi from data instead of fixing it with a kernel. The last layer of a classifier network is a linear model on learned features, the same shape as an SVM on ϕ(x)\phi(\mathbf{x}). See Neural Networks.
  • Kernel methods beyond SVMs include kernel PCA (see PCA and Dimensionality Reduction), Gaussian processes and kernel ridge regression.
  • One-class SVMs learn a boundary around normal data and flag what falls outside. See Anomaly Detection.
  • Margins in deep learning. Margin-based losses appear in face recognition and contrastive learning, which push matching pairs together and non-matching ones apart by at least a margin.

A bit of history

Vladimir Vapnik and Alexey Chervonenkis developed the maximum-margin idea and the statistical learning theory behind it in the Soviet Union from the 1960s. The kernel trick itself is older: Aizerman, Braverman and Rozonoer used kernels as dot products in a feature space in 1964. In 1992 Bernhard Boser, Isabelle Guyon and Vapnik, then at AT&T Bell Labs, combined maximum margins with kernels. In 1995 Corinna Cortes and Vapnik added the soft margin in Support-Vector Networks, giving the SVM in the form used today.

SVMs quickly matched the best neural networks of the time on handwritten digit recognition, and for about fifteen years they were the go-to classifier, helped by efficient solvers such as Platt's SMO (1998) and the LIBSVM library (2001 onward), which scikit-learn's SVC still wraps. The 2012 deep-learning breakthrough in image recognition (Convolutional Neural Networks) ended their reign on perceptual tasks, but they remain a strong, well-understood tool for small and medium datasets.

Try it

  1. In the hand example, add a new class +1+1 point at (1.5,1.5)(1.5, 1.5). Which points are the support vectors now? What is the new margin width?
  2. Verify the polynomial kernel trick for a=(2,−1)\mathbf{a} = (2, -1) and b=(1,3)\mathbf{b} = (1, 3) both ways.
  3. Harder: in the from-scratch code, try C = 0.1 and C = 1000. Count the support vectors (points with margin ≤ 1) each time. How does the margin width 2/∥w∥2/\lVert\mathbf{w}\rVert change?

Hint for 1: the new point has x1+x2=3x_1 + x_2 = 3, so it becomes the closest positive point. The boundary moves to x1+x2=2x_1 + x_2 = 2.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. In a trained SVM, which training points determine the boundary?

  2. You increase C in a soft-margin SVM from 0.1 to 1,000. What happens?

  3. What does the kernel trick let an SVM do?

  4. An RBF SVM reaches 99% training accuracy on noisy rings but does poorly on new data. Which setting is most likely to blame?

  5. For the point (2, 1), a linear SVM gives f(x) = 1/3. What does this tell you?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Course

Stanford CS229: Machine Learning

Stanford University · Advanced · Free

The classic mathematically rigorous ML course. Lecture notes and recorded lectures are free online.

Tool

LIBSVM

Chih-Chung Chang & Chih-Jen Lin · Advanced · Free

The classic SVM library that scikit-learn's SVC wraps. Its 'practical guide to SVM classification' is still worth reading.

Paper

Support-Vector Networks

Cortes & Vapnik · 1995 · Advanced · Paid

Introduced the soft-margin support vector machine with kernels.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/svm.md