Skip to content
ml-recall

Topic notes

Support Vector Machines

Support vector machines fit the maximum-margin hyperplane, allow margin errors through slack and C, depend only on their support vectors, and use kernels for non-linear boundaries.

3-min read AI-checked

Practise 38 questions Take a test

Key ideas

Formulas

Primal (soft margin) and dual1,2:

min⁡w,b,ξ12∥w∥2+C∑iξis.t. yi(w⊤xi+b)≥1−ξi, ξi≥0\min_{\mathbf{w}, b, \boldsymbol{\xi}} \tfrac12 \lVert \mathbf{w} \rVert^2 + C\sum_i \xi_i \quad \text{s.t. } y_i(\mathbf{w}^\top\mathbf{x}_i + b) \ge 1 - \xi_i,\ \xi_i \ge 0 max⁡α∑iαi−12∑i,jαiαjyiyjK(xi,xj)s.t. ∑iαiyi=0, 0≤αi≤C\max_{\boldsymbol\alpha} \sum_i \alpha_i - \tfrac12 \sum_{i,j} \alpha_i \alpha_j y_i y_j K(\mathbf{x}_i, \mathbf{x}_j) \quad \text{s.t. } \sum_i \alpha_i y_i = 0,\ 0 \le \alpha_i \le C

Kernels in scikit-learn3:

Kernel K(x,x′)K(\mathbf{x}, \mathbf{x}') Notes
linear x⊤x′\mathbf{x}^\top\mathbf{x}' plain linear SVM
polynomial (γ x⊤x′+r)d(\gamma\,\mathbf{x}^\top\mathbf{x}' + r)^d all monomials up to degree dd if r>0r > 0 (only degree dd if r=0r = 0)
RBF (Gaussian) exp⁡(−γ∥x−x′∥2)\exp(-\gamma \lVert \mathbf{x} - \mathbf{x}' \rVert^2) infinite-dimensional ϕ\phi; γ=1/(2σ2)\gamma = 1/(2\sigma^2)
sigmoid tanh⁡(γ x⊤x′+r)\tanh(\gamma\,\mathbf{x}^\top\mathbf{x}' + r)

Worked example

Negatives (−1,0),(0,−1),(0,0)(-1, 0), (0, -1), (0, 0); positives (2,1),(3,1),(2,2)(2, 1), (3, 1), (2, 2). The closest opposite pair is (0,0)(0,0) and (2,1)(2,1), so they are the support vectors and w\mathbf{w} points along their difference, w=c (2,1)\mathbf{w} = c\,(2, 1).

In code

import numpy as np
from sklearn.svm import SVC

X = np.array([[-1, 0], [0, -1], [0, 0], [2, 1], [3, 1], [2, 2]])
y = np.array([-1, -1, -1, 1, 1, 1])
clf = SVC(kernel="linear", C=1e6).fit(X, y)   # huge C ~ hard margin
print(clf.coef_, clf.intercept_)   # [[0.8 0.4]] [-1.]
print(clf.support_vectors_)        # [[0. 0.] [2. 1.]]
print(clf.dual_coef_)              # [[-0.4  0.4]]  = y_i * alpha_i
print(clf.decision_function([[1, 2]]))  # [0.6]

Common pitfalls

References

  1. Wikipedia: Support vector machine — Linear SVM (Hard-margin, Soft-margin); Nonlinear kernels; Computing the SVM classifier (Dual, Kernel trick, Sub-gradient descent); Properties — Issues; Extensions — Regression
  2. scikit-learn User Guide: Support Vector Machines — Sec. 1.4.7 Mathematical formulation (1.4.7.1 SVC, 1.4.7.2 SVR); Sec. 1.4.2 Regression
  3. scikit-learn User Guide: Support Vector Machines — Sec. 1.4.6 Kernel functions; Sec. 1.4.6.1 Parameters of the RBF Kernel; Sec. 1.4.5 Tips on Practical Use
  4. scikit-learn User Guide: Support Vector Machines — Sec. 1.4.1.2 Scores and probabilities
  5. Wikipedia: Kernel method — Mathematics: the kernel trick