Sign in

Support vector machine (SVM)

Support Vector Machine

A support vector machine: a two-class classifier that places the boundary as far as possible from the nearest points of each class, optionally in a kernel-induced feature space.

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 CC 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

  1. Code the two labels as −1-1 and +1+1, and compute the kernel matrix KK of similarities between all pairs of training points.
  2. Give every point a multiplier αi\alpha_i, starting at zero. The multipliers are the unknowns of the dual problem.
  3. Pick the pair of points that most violates the optimality conditions: one whose signed multiplier should rise and one whose should fall.
  4. Move that pair by the amount that is best for the dual objective, clipped so both multipliers stay between 0 and CC. Moving two at once keeps ∑iαiyi=0\sum_i \alpha_i y_i = 0.
  5. Repeat until the largest violation is below tol. This procedure is called sequential minimal optimisation, or SMO.
  6. Points with αi>0\alpha_i > 0 are the support vectors. Predict from the sign of f(x)=∑iαiyiK(xi,x)+bf(\mathbf{x}) = \sum_i \alpha_i y_i K(\mathbf{x}_i, \mathbf{x}) + b.

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 n2n^2 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

IfUse instead
You need probabilities, not just a decisionLogistic regression
The dataset has millions of rowsA linear model trained by stochastic gradient descent, or LightGBM
Features are mixed types with missing valuesA random forest or CatBoost

Math foundations

  1. The soft-margin problem

    min⁡w,b,ξ  12∥w∥2+C∑i=1nξis.t.yi(w⊤xi+b)≥1−ξi,    ξi≥0\min_{\mathbf{w}, b, \boldsymbol{\xi}} \; \frac{1}{2}\lVert \mathbf{w} \rVert^2 + C\sum_{i=1}^{n} \xi_i \quad \text{s.t.} \quad y_i(\mathbf{w}^\top \mathbf{x}_i + b) \ge 1 - \xi_i, \;\; \xi_i \ge 0

    Make the margin wide by keeping ∥w∥\lVert \mathbf{w} \rVert small, while paying CC for each unit by which a point falls short of the margin. The margin's width is 2/∥w∥2 / \lVert \mathbf{w} \rVert.

  2. The dual problem

    max⁡α  ∑i=1nαi−12∑i=1n∑j=1nαiαjyiyjKijs.t.0≤αi≤C,    ∑i=1nαiyi=0\max_{\boldsymbol{\alpha}} \; \sum_{i=1}^{n} \alpha_i - \frac{1}{2}\sum_{i=1}^{n}\sum_{j=1}^{n} \alpha_i \alpha_j y_i y_j K_{ij} \quad \text{s.t.} \quad 0 \le \alpha_i \le C, \;\; \sum_{i=1}^{n} \alpha_i y_i = 0

    An equivalent problem with one unknown per training point. The data appear only through KijK_{ij}, which is what allows a kernel to be swapped in.

  3. Kernels

    K(x,z)=x⊤z,K(x,z)=e−γ∥x−z∥2,K(x,z)=(γ x⊤z+c0)pK(\mathbf{x}, \mathbf{z}) = \mathbf{x}^\top \mathbf{z}, \qquad K(\mathbf{x}, \mathbf{z}) = e^{-\gamma \lVert \mathbf{x} - \mathbf{z} \rVert^2}, \qquad K(\mathbf{x}, \mathbf{z}) = \left(\gamma\, \mathbf{x}^\top \mathbf{z} + c_0\right)^{p}

    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.

  4. The decision function

    f(x)=∑i=1nαiyiK(xi,x)+bf(\mathbf{x}) = \sum_{i=1}^{n} \alpha_i y_i K(\mathbf{x}_i, \mathbf{x}) + b

    A weighted vote of the training points, each weighted by its similarity to x\mathbf{x}. Only support vectors have αi>0\alpha_i > 0, so only they need to be kept.

  5. Which points become support vectors

    αi=0⇒yif(xi)≥1,0<αi<C⇒yif(xi)=1,αi=C⇒yif(xi)≤1\alpha_i = 0 \Rightarrow y_i f(\mathbf{x}_i) \ge 1, \qquad 0 < \alpha_i < C \Rightarrow y_i f(\mathbf{x}_i) = 1, \qquad \alpha_i = C \Rightarrow y_i f(\mathbf{x}_i) \le 1

    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 CC.

  6. One SMO step

    t=Fi−FjKii+Kjj−2Kij,Fk=yk−∑lαlylKlkt = \frac{F_i - F_j}{K_{ii} + K_{jj} - 2K_{ij}}, \qquad F_k = y_k - \sum_{l} \alpha_l y_l K_{lk}

    For the chosen pair, αiyi\alpha_i y_i rises by tt and αjyj\alpha_j y_j falls by tt, after tt is clipped to keep both multipliers in [0,C][0, C]. This is the exact maximiser of the dual along that pair.

Symbols

xi,yi\mathbf{x}_i, y_i
training point i and its label, coded as -1 or +1
w,b\mathbf{w}, b
weights and bias of the separating plane
ξi\xi_i
slack: how far point i falls short of the margin
CC
soft-margin penalty
αi\alpha_i
dual multiplier of point i
KijK_{ij}
kernel value between points i and j
γ,c0,p\gamma, c_0, p
kernel width or scale, constant term and degree
f(x)f(\mathbf{x})
decision value: positive for one class, negative for the other
FkF_k
label minus current decision value (without bias) for point k
tt
size of one SMO step

Worked by hand

Two points on a line with a linear kernel and C=1C = 1: x1=1x_1 = 1 with y1=+1y_1 = +1 and x2=−1x_2 = -1 with y2=−1y_2 = -1. Start from α1=α2=0\alpha_1 = \alpha_2 = 0 and take one SMO step with i=1i = 1, j=2j = 2.

K11=1,K22=1,K12=−1K_{11} = 1, \quad K_{22} = 1, \quad K_{12} = -1
F1=y1−0=1,F2=y2−0=−1F_1 = y_1 - 0 = 1, \qquad F_2 = y_2 - 0 = -1
t=1−(−1)1+1−2(−1)=24=0.5t = \frac{1 - (-1)}{1 + 1 - 2(-1)} = \frac{2}{4} = 0.5
α1=0.5,α2=0.5\alpha_1 = 0.5, \qquad \alpha_2 = 0.5
w=α1y1x1+α2y2x2=0.5+0.5=1,b=0w = \alpha_1 y_1 x_1 + \alpha_2 y_2 x_2 = 0.5 + 0.5 = 1, \qquad b = 0

The decision function is f(x)=xf(x) = x. Both points satisfy yf(x)=1y f(x) = 1, so they lie exactly on the margin, and the margin's width is 2/∥w∥=22 / \lVert w \rVert = 2, 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 scores
Read 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

  1. 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 αi=0\alpha_i = 0 contributes nothing. Check that the optimality conditions still hold for the remaining points.

  2. 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.

  3. 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.

  4. Why does SMO change two multipliers at a time rather than one?
    A way to think about it

    The constraint ∑iαiyi=0\sum_i \alpha_i y_i = 0 must hold after every step. Ask how far a single multiplier can move while the others stay fixed.