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
- Builds on
- 12 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 12 concepts before this one
- What Is AI?
- Derivatives and Slopes
- Vectors
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- Logistic Regression
- 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.
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 with a weighted sum:
Here is the weight vector, the bias, and the dot product. It predicts class if and class if . SVMs label the classes and rather than 0 and 1, which makes the formulas tidier. The boundary is the line (or plane, or hyperplane in many dimensions) where . The vector points at right angles to it.
Measuring the margin
The SVM fixes the scale of and so that the closest points on each side have or exactly. The margin edges are then the lines , and the distance between them works out to:
where is the length of . A wider margin means a shorter . So "maximise the margin" becomes "make as small as possible, while classifying every point correctly with a score of at least 1":
Here is the label () of example . The product 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 : , , . Class : , , .
By symmetry the best boundary runs at 45°, so for some . The closest negative points, and , both have ; the closest positive point, , has . These are the support vectors, and they must score exactly and :
Subtracting gives , so , and then . The classifier is:
The boundary is the line , exactly midway. The margin is . Scikit-learn's SVC(kernel="linear") gives and on this data, matching.
Classify a new point : , so class . But 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:
It is zero for points correctly classified and outside the margin (), 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:
The hyperparameter sets the trade-off:
- Large : 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 : violations are cheap. The margin is wide and tolerant of outliers, at the risk of underfitting.
The 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 separates them. But add a second feature , and the orange points rise high while the blue points stay low, so a flat line separates them.
A feature map 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, . And for many useful feature maps, that dot product can be computed directly from the original vectors, cheaply, without ever building . A function that does this is called a kernel:
A worked example. For 2D inputs, let . Take and .
- The long way: and . Their dot product is .
- The short way: .
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:
Each weight 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: . No curves. Best when there are already many features, as in text.
- Polynomial: . Includes all feature products up to degree .
- RBF (radial basis function, or Gaussian): . 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") sets how far each support vector's influence reaches. Small means wide influence and smooth boundaries; large means each point only affects its immediate neighbourhood, giving wiggly boundaries that can wrap around individual points.
and 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 , 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 and , 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 and . They trade off against each other. Search them together on a log-spaced grid.
- Treating the score as a probability. is a distance-like score, not a probability. Use calibration (Platt scaling, which is what
probability=Truedoes) 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 can silently produce a model that predicts one class for everything, or memorises the training set. Scale, then grid-search and 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 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 . 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
- In the hand example, add a new class point at . Which points are the support vectors now? What is the new margin width?
- Verify the polynomial kernel trick for and both ways.
- Harder: in the from-scratch code, try
C = 0.1andC = 1000. Count the support vectors (points with margin ≤ 1) each time. How does the margin width change?Hint for 1: the new point has , so it becomes the closest positive point. The boundary moves to .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
scikit-learn: Support Vector Machines
SVC, LinearSVC and SVR explained, with kernels, the C and gamma parameters, and scaling advice.
Stanford CS229: Machine Learning
The classic mathematically rigorous ML course. Lecture notes and recorded lectures are free online.
LIBSVM
The classic SVM library that scikit-learn's SVC wraps. Its 'practical guide to SVM classification' is still worth reading.
Support-Vector Networks
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