Overview
Many lines can separate two groups of points. A support vector machine chooses the one with the widest empty band, called the margin, between the groups. Only the points on the edge of that band, the support vectors, decide where the boundary lies. The rest could be removed without changing it. When the groups overlap, a penalty sets how much a point inside the band costs. A kernel replaces the plain dot product between points with another similarity measure, which lets the same method draw curved boundaries without ever computing new features.
A short history
Vladimir Vapnik and Alexey Chervonenkis developed the maximum margin classifier in the Soviet Union in the 1960s. In 1992 Bernhard Boser, Isabelle Guyon and Vapnik added the kernel trick, which allows curved boundaries, and in 1995 Corinna Cortes and Vapnik published the soft margin version that tolerates overlapping classes. SVMs were among the most accurate classifiers from the late 1990s until deep learning took over image and text tasks.
How it works
- Code the two labels as and , and compute the kernel matrix of similarities between all pairs of training points.
- Give every point a multiplier , starting at zero. The multipliers are the unknowns of the dual problem.
- Pick the pair of points that most violates the optimality conditions: one whose signed multiplier should rise and one whose should fall.
- Move that pair by the amount that is best for the dual objective, clipped so both multipliers stay between 0 and . Moving two at once keeps .
- Repeat until the largest violation is below tol. This procedure is called sequential minimal optimisation, or SMO.
- Points with are the support vectors. Predict from the sign of .
Watch out for
- The RBF and polynomial kernels depend on distances and dot products, so a feature with a large scale dominates them. Standardise the features first.
- A large gamma makes each support vector influence only its immediate surroundings, so the model memorises the training points. A very small gamma makes the boundary almost linear.
- The kernel matrix has entries and the template stores it in full, so memory and time grow quickly with the number of rows.
- The output of decision_function is a signed distance-like score, not a probability. Do not read it as one without a separate calibration step.
Use cases
When to use it
Small and medium two-class problems with clean, scaled features, especially when there are more features than rows or a curved boundary is needed and an RBF kernel can supply it.
In industry
- Text classification
- Sorting documents by topic or sentiment from high-dimensional word features, where linear SVMs are fast and accurate.
- Bioinformatics
- Classifying tissue samples from gene expression data, which has many features and few samples.
- Handwriting recognition
- Recognising handwritten digits, an early benchmark on which kernel SVMs matched the neural networks of the 1990s.
Choosing it: what must hold
- A two-class problem, or a multiclass one split into several two-class problems.
- Scaled numeric features.
- For kernel SVMs, a training set of at most tens of thousands of rows, since cost grows faster than linearly with rows.
- Time to tune the penalty C and the kernel width on validation data.
When to choose something else
| If | Use instead |
|---|---|
| You need probabilities, not just a decision | Logistic regression |
| The dataset has millions of rows | A linear model trained by stochastic gradient descent, or LightGBM |
| Features are mixed types with missing values | A random forest or CatBoost |
Math foundations
The soft-margin problem
Make the margin wide by keeping small, while paying for each unit by which a point falls short of the margin. The margin's width is .
The dual problem
An equivalent problem with one unknown per training point. The data appear only through , which is what allows a kernel to be swapped in.
Kernels
Linear, RBF and polynomial. Each is a dot product in some feature space, computed without building that space. The RBF kernel is near 1 for close points and near 0 for distant ones.
The decision function
A weighted vote of the training points, each weighted by its similarity to . Only support vectors have , so only they need to be kept.
Which points become support vectors
The optimality conditions. Points safely outside the margin have no say, points exactly on it have a multiplier strictly between the bounds, and points inside or misclassified sit at the cap .
One SMO step
For the chosen pair, rises by and falls by , after is clipped to keep both multipliers in . This is the exact maximiser of the dual along that pair.
Symbols
- training point i and its label, coded as -1 or +1
- weights and bias of the separating plane
- slack: how far point i falls short of the margin
- soft-margin penalty
- dual multiplier of point i
- kernel value between points i and j
- kernel width or scale, constant term and degree
- decision value: positive for one class, negative for the other
- label minus current decision value (without bias) for point k
- size of one SMO step
Worked by hand
Two points on a line with a linear kernel and : with and with . Start from and take one SMO step with , .
The decision function is . Both points satisfy , so they lie exactly on the margin, and the margin's width is , the full distance between them.
Visual example
Loading the example.
Try this
- Lower C: the margin widens and lets a few points sit inside it.
- Raise C: the margin tightens around the closest points.
Code sample
import numpy as np
from impl import SVM
from config import SVMConfig
rng = np.random.default_rng(0)
X = rng.uniform(-1, 1, size=(200, 2))
y = np.where((X**2).sum(axis=1) < 0.4, "inside", "outside") # a disc: not linearly separable
model = SVM(SVMConfig(kernel="rbf", gamma=2.0, C=10.0)).fit(X, y)
print((model.predict(X) == y).mean()) # training accuracy, about 0.99
print(len(model.support_)) # number of support vectors
print(model.decision_function(X[:3])) # signed distance-like scoresRead the implementation (99 lines)
"""Support vector machine for two classes, trained on the dual problem by SMO.
NumPy only. With labels y_i in {-1, +1} and kernel matrix K, the dual problem is
maximise sum_i a_i - 0.5 * sum_ij a_i a_j y_i y_j K_ij
subject to 0 <= a_i <= C and sum_i a_i y_i = 0
and the decision function is f(x) = sum_i a_i y_i K(x_i, x) + b.
"""
from __future__ import annotations
import numpy as np
try:
from .config import SVMConfig
except ImportError: # run from the template's own folder
from config import SVMConfig
class SVM:
"""Kernel SVM. After `fit`: `alpha_` (n,), `support_` (indices), `dual_coef_`, `support_vectors_`, `b_`."""
def __init__(self, config: SVMConfig | None = None) -> None:
self.config = config or SVMConfig()
self.classes_: np.ndarray | None = None
self.alpha_: np.ndarray | None = None
self.support_: np.ndarray | None = None
self.support_vectors_: np.ndarray | None = None
self.dual_coef_: np.ndarray | None = None # alpha_i * y_i for the support vectors
self.coef_: np.ndarray | None = None # primal weights, linear kernel only
self.b_ = 0.0
self.n_iter_ = 0
def kernel(self, A: np.ndarray, B: np.ndarray) -> np.ndarray:
"""Kernel matrix between the rows of A (n, d) and the rows of B (m, d). Returns shape (n, m)."""
cfg = self.config
if cfg.kernel == "linear":
return A @ B.T
if cfg.kernel == "poly":
return (cfg.gamma * (A @ B.T) + cfg.coef0) ** cfg.degree
sq = (A**2).sum(axis=1)[:, None] + (B**2).sum(axis=1)[None, :] - 2.0 * (A @ B.T)
return np.exp(-cfg.gamma * np.maximum(sq, 0.0))
def fit(self, X: np.ndarray, y: np.ndarray) -> "SVM":
"""Train. X: features, shape (n, d). y: labels with exactly two distinct values, shape (n,)."""
X = np.asarray(X, dtype=float)
y = np.asarray(y)
if X.ndim != 2 or len(X) != len(y):
raise ValueError("X must have shape (n, d) and y must have n entries")
self.classes_ = np.unique(y)
if len(self.classes_) != 2:
raise ValueError(f"y must hold exactly two classes, found {len(self.classes_)}")
sign = np.where(y == self.classes_[1], 1.0, -1.0)
C, n = self.config.C, len(X)
K = self.kernel(X, X)
alpha = np.zeros(n)
g = np.zeros(n) # g_k = sum_i alpha_i y_i K_ik, the decision value without the bias
self.n_iter_ = 0
up_value, low_value = 1.0, -1.0
for _ in range(self.config.max_iter):
# At the optimum there is a b with y_k - g_k <= b on the "up" set and >= b on the "low" set.
f = sign - g
can_go_up = ((sign > 0) & (alpha < C)) | ((sign < 0) & (alpha > 0))
can_go_down = ((sign > 0) & (alpha > 0)) | ((sign < 0) & (alpha < C))
i = int(np.argmax(np.where(can_go_up, f, -np.inf)))
j = int(np.argmin(np.where(can_go_down, f, np.inf)))
up_value, low_value = f[i], f[j]
if up_value - low_value < self.config.tol:
break
# Move alpha_i y_i up by t and alpha_j y_j down by t: keeps sum alpha y = 0.
curvature = max(K[i, i] + K[j, j] - 2.0 * K[i, j], 1e-12)
t = (up_value - low_value) / curvature
t = min(t, C - alpha[i] if sign[i] > 0 else alpha[i])
t = min(t, alpha[j] if sign[j] > 0 else C - alpha[j])
alpha[i] += sign[i] * t
alpha[j] -= sign[j] * t
g += t * (K[:, i] - K[:, j])
self.n_iter_ += 1
self.alpha_ = alpha
self.b_ = float(0.5 * (up_value + low_value))
self.support_ = np.flatnonzero(alpha > 1e-8)
self.support_vectors_ = X[self.support_]
self.dual_coef_ = (alpha * sign)[self.support_]
self.coef_ = self.dual_coef_ @ self.support_vectors_ if self.config.kernel == "linear" else None
return self
def decision_function(self, X: np.ndarray) -> np.ndarray:
"""f(x) = sum_i alpha_i y_i K(x_i, x) + b. Positive means `classes_[1]`. X: (n, d). Returns (n,)."""
if self.dual_coef_ is None:
raise RuntimeError("call fit before predicting")
return self.kernel(np.asarray(X, dtype=float), self.support_vectors_) @ self.dual_coef_ + self.b_
def predict(self, X: np.ndarray) -> np.ndarray:
"""Predicted labels, taken from `classes_`. X: (n, d). Returns shape (n,)."""
return self.classes_[(self.decision_function(X) >= 0).astype(int)]
def score(self, X: np.ndarray, y: np.ndarray) -> float:
"""Accuracy: the share of rows whose predicted label equals y."""
return float((self.predict(X) == np.asarray(y)).mean())- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Generate points inside a disc as one class and points in a ring around it as the other. Fit SVM with SVMConfig kernel set to linear and then to rbf, and compare score. With the rbf kernel, try gamma values 0.01, 1 and 100 and for each record the training score, the score on held-out points and the number of entries in support_.
Check on learning
- Remove a training point that is not a support vector and retrain. Why is the boundary unchanged, and what does that say about which data matters?
A way to think about it
Look at the decision function: a point with contributes nothing. Check that the optimality conditions still hold for the remaining points.
- As C grows very large, what happens to the margin and to the number of points allowed inside it? When is a small C the better choice?
A way to think about it
C is the price of a violation. Consider one mislabelled point sitting deep in the other class, and what the boundary must do to accommodate it at a high price.
- With an RBF kernel and a very large gamma, training accuracy is perfect and test accuracy is poor. Explain this in terms of what each support vector contributes.
A way to think about it
When gamma is large the kernel is close to zero unless two points nearly coincide. The decision function becomes a set of small islands around training points.
- Why does SMO change two multipliers at a time rather than one?
A way to think about it
The constraint must hold after every step. Ask how far a single multiplier can move while the others stay fixed.