Algorithmcore
One-class support vector machine
Also called one-class SVM, Scholkopf novelty detector.
Learns a region in a kernel feature space that holds most of the training data, by separating the data from the origin with maximum margin, and flags new points outside it.
- Solves
- Anomaly detection
- Time
- O(n^2 d + r n) worst
- Space
- O(n^2) extra
- Where
- d = the dimension; n = the number of training points; r = the number of SMO steps
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Bernhard Scholkopf, John C. Platt, John Shawe Taylor, Alex J. Smola, Robert C. Williamson, 2001
A one-class support vector machine learns a region that holds most of the normal data, from normal data alone, and flags new points that fall outside it. It is a detector for the anomaly detection problem in its novelty form: the training set is assumed clean, and the question is whether a new point looks like it. The method maps the data into a feature space with a kernel and finds the hyperplane that separates the data from the origin with the largest margin. The side of the data is the region. A parameter controls how tight the region is. Scholkopf, Platt, Shawe-Taylor, Smola and Williamson (2001) proved that is an upper bound on the fraction of training points left outside and a lower bound on the fraction of support vectors.
In plain words
Imagine drawing a fence around a herd of sheep in a field. You want the fence as tight as you can, but you allow a few sheep at the edge to be outside, so that one stray does not make the whole fence huge. The parameter says what share of the sheep you allow outside. Later, an animal outside the fence is flagged.
The fence is not a circle or a box. It is built from bumps around chosen training points, the support vectors. Where there are many training points close together, the bumps add up and the inside is large. Far from all training points, the sum is small and the point is outside.
The problem
The input is a training set , a parameter , a kernel , and a tolerance . Here is the Gaussian kernel with . Let be a feature map with . The primal problem is
Its dual, with and , is
The output is a feasible with , where is the optimum, and an offset . The decision function is , and is flagged when .
The algorithm
The solver is sequential minimal optimization on the dual. Each step moves weight between two coordinates, the pair that violates the optimality conditions the most. Let be the gradient of .
ONE-CLASS-SVM(x[1..n], ν, k, ε)- 1
C ← 1 / (ν n); K[i][j] ← k(x_i, x_j) for all i, j - 2
a ← C on the first ⌊ν n⌋ coordinates, 1 - ⌊ν n⌋ C on the next one, 0 on the rest - 3
G ← K a - 4
loop - 5
i ← argmin of G_r over {r : a_r < C}; j ← argmax of G_r over {r : a_r > 0} - 6
if G_j - G_i ≤ ε then leave the loop - 7
t ← min((G_j - G_i) / (K_ii + K_jj - 2 K_ij), C - a_i, a_j) - 8
a_i ← a_i + t; a_j ← a_j - t - 9
G ← G + t (K[·][i] - K[·][j]) - 10
ρ ← the mean of G_r over the free r (0 < a_r < C), or (G_i + G_j) / 2 if there are none - 11
return a, ρ ▷ g(z) = Σ a_r k(x_r, z) - ρ
Line L2 is the start point of the paper: a fraction of the weights at the upper bound and the rest of the mass on one more point, so that . Line L5 picks the coordinate that can grow and has the smallest gradient, and the coordinate that can shrink and has the largest gradient. Moving weight from to changes by . Line L7 takes the minimizing and clips it to the box. Line L9 updates the gradient in time. The code replaces a denominator below by ; the clip keeps the step inside the box.
Line L10 sets from the optimality conditions. At the optimum, for each free coordinate, when and when . On the training set, . So points with are inside the region, free points are on its boundary, and only points with can be outside.
Example
Take the six points on a line, and . Then , and line L2 starts with . The solver stops at the values in the table, with .
| point | status | ||
|---|---|---|---|
| 0 | 0.2778 | at the bound | -0.0589 |
| 1 | 0.0941 | free | 0.0000 |
| 2 | 0 | inside | 0.0178 |
| 3 | 0.0725 | free | 0.0000 |
| 4 | 0.2778 | at the bound | -0.0469 |
| 9 | 0.2778 | at the bound | -0.2047 |
The region where is about the interval from 1 to 3; for example , and . The point 9 has the most negative value, and new points such as 6 () are flagged. Three of six training points, a fraction 0.5, are outside, which is at most . Five of six are support vectors, a fraction 0.83, which is at least . With a smaller the bound is larger, fewer points reach it, and the region grows to hold more of the cluster.
Correctness
The dual is a convex quadratic program over a compact set, so it has an optimum . The steps keep feasible: line L7 never moves above or below 0, and the sum does not change. Each step with lowers strictly. When the loop stops, let and with . For any feasible , convexity gives , and the sign pattern of gives . So . The same bound gives when and when .
The -property (Proposition 3 of the paper, which assumes ) follows from the box. A training point with has , and at most coordinates can equal when they sum to 1. So at most a fraction of the points are outside. A sum of 1 with terms at most needs at least nonzero terms, so at least a fraction are support vectors. Part (iii) of the proposition says that both fractions tend to as grows, for i.i.d. data from a distribution with no discrete part and an analytic kernel that is not constant. The proofs section below gives the details.
Keerthi and Gilbert (2002) prove that SMO with the maximal violating pair stops after finitely many steps for any on the dual of the SVM classifier, which is also a convex quadratic with box constraints and one linear equality. The code does not depend on this: it stops with an error after a fixed number of steps.
Proof: SMO on the one-class dual stays feasible, decreases the objective, and stops within epsilon of the optimum with the nu-propertyfull
Setting. is the kernel matrix, positive semidefinite, with , and the feasible set is . It is not empty, because . The objective is , a convex function, and is compact, so has a minimum on . Write , and .
Lemma 1 (start point). The vector of line L2 is in .
Proof. Let . Then , so the remainder is in . It is also less than , because gives . If there is no remainder, and . The code clips the remainder to , which only matters for rounding. All entries are in and they sum to 1.
Lemma 2 (one step). Suppose at line L6, with , . Then lines L7 to L9 keep in , keep , and lower by at least .
Proof. Since and , and . Also , since would give . Let , and let be the value the code uses. The step is positive. After line L8, , , and the sum is unchanged, so . Since , line L9 keeps . Along the direction ,
Since and , we have , so the change is at most .
Termination. The loop of line L4 runs at most max_iter times in the code, and it raises an error if it has not stopped by then; it never returns a wrong answer. Keerthi and Gilbert (2002) prove that for the maximal violating pair rule stops after finitely many steps on the SVM classifier dual, which is a convex quadratic with box constraints and one linear equality, the same form as here. By Lemma 2 the values of strictly decrease, so no state repeats.
Lemma 3 (the stop gives an epsilon optimal point). If the loop stops at line L6 with , then .
Proof. Let and . Then . If , then , so and . If , then , so and . Let . Then
Also . So . Because is convex and differentiable with gradient at , . Taking optimal gives .
If instead the loop stops because is empty, then every , so , , and has one point, which is optimal.
Lemma 4 (the offset and the approximate KKT conditions). At the stop with , the value of line L10 is in . For each training point, , and if , and if .
Proof. A free coordinate is in both and , so its gradient is in , and so is a mean of such values. If there is no free coordinate, . By definition , using the symmetry of . If , then . If , then .
When , the code sets , so for all , which is the condition for coordinates at the bound .
Theorem (the nu-property, finite form). At the stop, the number of training points with is at most , and the number of support vectors, the points with , is at least .
Proof. By Lemma 4, a point with cannot have , so . If coordinates equal , then , so . For the second part, if coordinates are positive, then , so .
With this is parts (i) and (ii) of Proposition 3 of Scholkopf et al. (2001), for the points with . By Lemmas 1 to 4 and the theorem, the procedure returns a feasible with , an offset that satisfies the optimality conditions up to , and a decision function with the -property.
Complexity
The cost is in the real-RAM model, with one unit for each arithmetic operation and each evaluation of .
- Kernel matrix. Line L1 takes time and space.
- Each step. Lines L5 and L9 scan coordinates, so a step costs , and steps cost . There is no useful bound on in terms of alone.
- Prediction. costs , where is the number of support vectors, at least .
- Large data. Solvers such as LIBSVM keep only a cache of kernel rows instead of all of , so the space is plus the cache.
Properties
- The meaning of . is an upper bound on the fraction of training outliers and a lower bound on the fraction of support vectors, exactly, for every data set (with ). This is the theorem above. The false alarm rate on new normal data is close to the training fraction only for large ; that is the asymptotic part (iii) and a heuristic for finite data.
- Unique solution. For distinct points the Gaussian kernel matrix is positive definite, so is strictly convex and the optimal is unique.
- Same as a ball. For kernels with constant , such as the Gaussian kernel, the problem is equivalent to the smallest ball in feature space that holds most of the data, the support vector data description (Section 3 of the paper).
- Sparse. Points with , the inside points, do not enter . Only the support vectors are kept.
- Kernel width. A large makes narrow bumps and a region that hugs each training point; a small makes a smooth region. Choosing without labeled anomalies is a heuristic.
Variants and improvements
- Other kernels. Any positive definite kernel works. With a kernel whose is not constant, the method differs from the ball of SVDD.
- Second order working sets. LIBSVM chooses by the largest decrease of for the pair, using the second derivative, instead of the largest gradient. This needs fewer steps.
- Shrinking and caching. Coordinates that stay at a bound for many steps are removed from the scan for a while, and kernel rows are cached.
- . All weights equal , and is a Parzen window density estimate minus a constant.
When to use it
Use it when there is a clean set of normal examples, the data are numeric and of moderate size (up to some tens of thousands of points with a standard solver), and a smooth boundary in a kernel space fits the normal class. It gives a direct control of the training false alarm rate through . Use the isolation forest for very large data, and the local outlier factor when the anomalies are local to dense clusters.
Pitfalls
- The wrong upper bound. The box is . If line L1 uses , the box never binds, the -property fails, and no point can be outside on the training set.
- Unscaled features. The Gaussian kernel uses Euclidean distances, so a feature with a large range dominates. Scale the features before line L1.
- from a bound coordinate. If line L10 takes from a point at or , can be off by the slack of that point. Take the mean over free coordinates, as line L10 does, and fall back to the midpoint only when there are none.
- The stop test on the wrong sets. Line L5 must take among coordinates below and among coordinates above 0. Taking the minimum and maximum over all coordinates can choose a pair that cannot move, and the loop then never stops.
- Contaminated training data. The method assumes clean normal training data. Attacks or faults in the training set enlarge the region and are then accepted. The value of only limits how many training points are left outside.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/one-class-svm/. The authors are listed in prov/NCSJF7.jsonl.
import math
from dataclasses import dataclass
from typing import Sequence
Point = Sequence[float]
def gaussian_kernel(a: Point, b: Point, gamma: float) -> float:
"""k(a, b) = exp(-gamma |a - b|^2). Cost: O(d)."""
return math.exp(-gamma * sum((u - v) ** 2 for u, v in zip(a, b)))
@dataclass(frozen=True)
class OneClassSVM:
points: tuple[tuple[float, ...], ...]
alpha: tuple[float, ...]
rho: float
gamma: float
def dual_objective(alpha: Sequence[float], k: Sequence[Sequence[float]]) -> float:
"""f(alpha) = (1/2) alpha^T K alpha. Cost: O(n^2)."""
n = len(alpha)
return 0.5 * sum(alpha[i] * k[i][j] * alpha[j] for i in range(n) for j in range(n))
def fit_one_class_svm(
x: Sequence[Point], nu: float, gamma: float, eps: float = 1e-6, max_iter: int = 1_000_000
) -> OneClassSVM:
"""Train the one-class SVM of Scholkopf et al. with a Gaussian kernel.
Solves min (1/2) a^T K a subject to 0 <= a_i <= 1/(nu n) and sum a_i = 1 by
sequential minimal optimization on the maximal violating pair. On return the
dual value is within eps of the optimum. Precondition: n >= 1, 0 < nu <= 1,
gamma > 0, eps > 0. Cost: Theta(n^2 d) for the kernel matrix and O(n) per
iteration; O(n^2) space.
"""
n = len(x)
if n < 1 or not 0.0 < nu <= 1.0 or gamma <= 0.0 or eps <= 0.0:
raise ValueError("need n >= 1, 0 < nu <= 1, gamma > 0, eps > 0")
c = 1.0 / (nu * n) # @line L1
k = [[gaussian_kernel(x[i], x[j], gamma) for j in range(n)] for i in range(n)]
a = [0.0] * n
full = min(n, int(nu * n))
for i in range(full): # @line L2
a[i] = c
if full < n:
a[full] = min(c, max(0.0, 1.0 - full * c))
g = [sum(k[r][s] * a[s] for s in range(n)) for r in range(n)] # @line L3
up = lo_g = 0.0
for _ in range(max_iter): # @line L4
up_set = [r for r in range(n) if a[r] < c]
down_set = [r for r in range(n) if a[r] > 0.0]
if not up_set:
break
i = min(up_set, key=lambda r: g[r]) # @line L5
j = max(down_set, key=lambda r: g[r])
lo_g, up = g[i], g[j]
if up - lo_g <= eps: # @line L6
break
eta = max(k[i][i] + k[j][j] - 2.0 * k[i][j], 1e-12)
t = min((up - lo_g) / eta, c - a[i], a[j]) # @line L7
a[i] = c if t == c - a[i] else a[i] + t # @line L8
a[j] = 0.0 if t == a[j] else a[j] - t
for r in range(n): # @line L9
g[r] += t * (k[r][i] - k[r][j])
else:
raise RuntimeError("no convergence within max_iter")
free = [g[r] for r in range(n) if 0.0 < a[r] < c]
if not any(a[r] < c for r in range(n)):
rho = max(g) # nu = 1: every point is at the upper bound
elif free:
rho = sum(free) / len(free) # @line L10
else:
rho = (lo_g + up) / 2.0
pts = tuple(tuple(float(v) for v in p) for p in x)
return OneClassSVM(pts, tuple(a), rho, gamma) # @line L11
def decision_function(model: OneClassSVM, z: Point) -> float:
"""f(z) = sum_i a_i k(x_i, z) - rho; z is flagged as novel when f(z) < 0. Cost: O(n d)."""
s = sum(ai * gaussian_kernel(xi, z, model.gamma) for ai, xi in zip(model.alpha, model.points) if ai > 0.0)
return s - model.rho
test_one_class_svm.py 125 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/one-class-svm/. The authors are listed in prov/NCSJF7.jsonl.
import math
import random
import pytest
from one_class_svm import decision_function, dual_objective, fit_one_class_svm, gaussian_kernel
EPS = 1e-7
def kernel_matrix(x, gamma):
return [[gaussian_kernel(p, q, gamma) for q in x] for p in x]
def project(v, c):
"""Euclidean projection onto {0 <= a_i <= c, sum a_i = 1}, exact, by the breakpoints of tau."""
def mass(tau):
return sum(min(c, max(0.0, vi - tau)) for vi in v)
pts = sorted({vi for vi in v} | {vi - c for vi in v})
lo_t, hi_t = pts[0] - 1.0, pts[-1]
for b in pts:
if mass(b) >= 1.0:
lo_t = b
else:
hi_t = b
break
# mass is linear on [lo_t, hi_t]; solve mass(tau) = 1.
m_lo, m_hi = mass(lo_t), mass(hi_t)
tau = lo_t if m_lo == m_hi else lo_t + (m_lo - 1.0) * (hi_t - lo_t) / (m_lo - m_hi)
return [min(c, max(0.0, vi - tau)) for vi in v]
def oracle_value(k, c, iters=100):
"""Accelerated projected gradient on the same dual, from the uniform point."""
n = len(k)
step = 1.0 / n # the largest eigenvalue of a Gaussian kernel matrix is at most n
a = [1.0 / n] * n
y, t = a[:], 1.0
for _ in range(iters):
grad = [sum(k[r][s] * y[s] for s in range(n)) for r in range(n)]
a_new = project([y[r] - step * grad[r] for r in range(n)], c)
t_new = (1 + math.sqrt(1 + 4 * t * t)) / 2
y = [a_new[r] + (t - 1) / t_new * (a_new[r] - a[r]) for r in range(n)]
a, t = a_new, t_new
return dual_objective(a, k), a
def check_kkt(model, x, nu, eps):
n = len(x)
c = 1.0 / (nu * n)
a = model.alpha
assert all(0.0 <= ai <= c for ai in a)
assert math.isclose(sum(a), 1.0, abs_tol=1e-12)
f = [decision_function(model, p) for p in x]
for ai, fi in zip(a, f):
if ai < c:
assert fi >= -eps - 1e-9
if ai > 0.0:
assert fi <= eps + 1e-9
# Proposition 3 (i) and (ii): outliers (f < -eps) are at most nu n, support vectors at least nu n.
assert sum(fi < -eps - 1e-9 for fi in f) <= nu * n + 1e-9
assert sum(ai > 0.0 for ai in a) >= nu * n - 1e-9
def test_small_example() -> None:
x = [(0.0,), (1.0,), (2.0,), (3.0,), (4.0,), (9.0,)]
model = fit_one_class_svm(x, 0.6, 0.1, eps=1e-10)
check_kkt(model, x, 0.6, 1e-10)
want_alpha = [0.2778, 0.0941, 0.0, 0.0725, 0.2778, 0.2778]
assert all(abs(a - w) < 5e-5 for a, w in zip(model.alpha, want_alpha))
assert abs(model.rho - 0.5075) < 5e-5
f = [decision_function(model, p) for p in x]
want_f = [-0.0589, 0.0, 0.0178, 0.0, -0.0469, -0.2047]
assert all(abs(a - w) < 5e-5 for a, w in zip(f, want_f))
assert decision_function(model, (6.0,)) < 0 < decision_function(model, (2.5,))
def test_edges() -> None:
one = fit_one_class_svm([(3.0, 4.0)], 1.0, 1.0)
assert one.alpha == (1.0,)
every = fit_one_class_svm([(0.0,), (1.0,), (5.0,)], 1.0, 1.0)
assert all(math.isclose(ai, 1 / 3) for ai in every.alpha)
for bad in ((0.0, 1.0), (1.5, 1.0), (0.5, 0.0)):
with pytest.raises(ValueError):
fit_one_class_svm([(0.0,), (1.0,)], *bad)
with pytest.raises(ValueError):
fit_one_class_svm([], 0.5, 1.0)
def test_random_against_projected_gradient() -> None:
rng = random.Random(123)
for _ in range(500):
n = rng.randint(2, 6)
d = rng.randint(1, 2)
x = [tuple(rng.uniform(-2, 2) for _ in range(d)) for _ in range(n)]
nu = rng.choice([1 / n, 0.3, 0.5, 0.8, 1.0, rng.uniform(0.05, 1.0)])
gamma = rng.choice([0.2, 1.0, 3.0])
model = fit_one_class_svm(x, nu, gamma, eps=EPS)
k = kernel_matrix(x, gamma)
f_smo = dual_objective(model.alpha, k)
f_pg, _ = oracle_value(k, 1.0 / (nu * n))
# The projected gradient point is feasible, so f_pg >= f*, and SMO is within eps of f*.
assert f_smo <= f_pg + EPS + 1e-12
assert f_pg - f_smo <= 1e-4
check_kkt(model, x, nu, EPS)
def test_nu_fractions_on_a_sample() -> None:
rng = random.Random(8)
x = [(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(120)]
nu = 0.2
model = fit_one_class_svm(x, nu, 0.5, eps=1e-5)
f = [decision_function(model, p) for p in x]
outliers = sum(v < -1e-5 for v in f) / len(x)
svs = sum(a > 0.0 for a in model.alpha) / len(x)
assert outliers <= nu <= svs
# Measurement on this seed: both fractions are close to nu, as Proposition 3 (iii) predicts for large n.
assert outliers >= 0.1 and svs <= 0.35
far = decision_function(model, (5.0, 5.0))
assert far < 0 and far < min(f)
History
Scholkopf, Platt, Shawe-Taylor, Smola and Williamson presented the method in 1999 and published the full version, with the -property, the SMO solver and the analysis, in Neural Computation in 2001. Tax and Duin had proposed the support vector data description, a smallest ball in feature space, at about the same time, and the two methods coincide for the Gaussian kernel. The one-class SVM became a standard novelty detector and is part of common machine learning libraries. In security it has been applied to host and network anomaly detection, where the need for clean training data is a main limit.
References
- Bernhard Scholkopf, John C. Platt, John Shawe-Taylor, Alex J. Smola and Robert C. Williamson, Estimating the support of a high-dimensional distribution, Neural Computation 13(7), 2001, Section 3 (the primal problem, the dual eq. 3.11, the offset rho from eq. 3.12, and the relation to a ball for kernels with constant k(x, x)), Proposition 3 (the nu-property), Section 4 (the SMO solver and its initialization)
- S. Sathiya Keerthi and Elmer G. Gilbert, Convergence of a generalized SMO algorithm for SVM classifier design, Machine Learning 46, pages 351 to 360, 2002, the proof that SMO with the maximal violating pair stops after finitely many steps for any positive tolerance
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag NCSJF7 Edit this page History Report an error Markdown