Algorithmadvanced
Support vector data description
Also called SVDD.
Finds the smallest sphere in a kernel feature space that holds most training points, and flags 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
- David M. J. Tax, Robert P. W. Duin, 1999
The support vector data description, SVDD, describes a set of normal data by a ball: the smallest sphere that holds most of the points. A new point outside the sphere is flagged. With a plain inner product the ball is a ball in the input space. With a kernel, the ball lives in a feature space, and its boundary in the input space can take almost any shape around the data. A parameter lets some training points fall outside, so that a few strays do not inflate the sphere. Tax and Duin (1999, 2004) proposed it for one-class classification, the novelty form of the anomaly detection problem.
In plain words
Put a rubber balloon around a cloud of points and let it shrink until it touches the outermost points. That is the smallest ball that holds them all. One far point would keep the balloon huge, so you pay a fine for each point you leave outside, and you choose the fine. A small fine lets more points out and gives a tighter balloon.
The center of the balloon is a weighted mean of a few training points, the support vectors. Only the points on the skin or outside it get a weight. To test a new point, measure its distance to the center and compare it with the radius.
The problem
The input is a training set , a kernel with feature map , a penalty with , and a tolerance . The primal problem is
With its dual, written as a minimization, is
The center is , and the squared distance of a point to it is
The output is a feasible with and the squared radius . A point is flagged when . For the bound never binds and the problem is the minimum enclosing ball of the points . For the constraints cannot hold.
The algorithm
The solver is sequential minimal optimization on the dual, as for the one-class SVM. Let be the gradient of . On the training points, .
SVDD(x[1..n], C, k, ε)- 1
K[i][j] ← k(x_i, x_j) for all i, j - 2
a ← C on the first ⌊1/C⌋ coordinates, 1 - ⌊1/C⌋ C on the next one, 0 on the rest - 3
G ← 2 K a - diag(K) - 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) / (2 (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 + 2 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, R² = aᵀ K a - λ ▷ flag z when D(z) > R²
Line L2 starts from a feasible point; for it puts all the weight on the first point. Moving weight from to changes by , and line L7 takes the minimizing clipped to the box. Line L10 reads the radius from the free coordinates. These are the points on the sphere, so for each of them , which is . Points with are inside or on the sphere, and points with are on or outside it.
Example
Take the six points , , , , and with the linear kernel , so the ball is an ordinary disk.
| nonzero weights | center | outside | ||
|---|---|---|---|---|
| 1 | (0,0): 0.2569, (0,2): 0.2569, (6,1): 0.4861 | (2.9167, 1) | 9.5069 | none |
| 0.5 | the same | (2.9167, 1) | 9.5069 | none |
| 0.25 | (0,0), (0,2), (6,1): 0.25 each; (2,0), (2,2): 0.125 each | (2, 1) | 1.0 | (0,0), (0,2), (6,1) |
With the result is the smallest disk that holds all six points: the circle through , and , with center and . The point makes it large. With no weight reaches the bound, so the disk does not change. With at most weights can be at the bound. The solution leaves three points outside and shrinks the disk to center and radius 1, with and on the circle and on it as well. The center is still pulled toward , because a point outside keeps the weight .
Correctness
The dual is a convex quadratic program over a compact set. As for the one-class SVM, each step keeps feasible and lowers strictly, and the stop test gives by convexity: for any feasible , . The same bound gives when and when . So at most training points are outside the sphere by more than , and at least have a positive weight. For the sphere is within of the minimum enclosing ball in squared radius. The proofs section below gives the details.
Proof: SMO on the SVDD dual stops within epsilon of the optimum, gives a consistent radius, and for C at least 1 gives the minimum enclosing ballfull
Setting. is a positive semidefinite kernel matrix with feature map , , and , which is not empty because . The objective is convex, and is compact, so has a minimum on . Write , , , and .
Lemma 1 (distances). .
Proof. , and .
Lemma 2 (start point). Line L2 gives a point of . With ones at value (or one coordinate at 1 when ), and the remainder is in . If the remainder is 0.
Lemma 3 (one step). If at line L6, with and , then lines L7 to L9 keep , keep , and lower by at least .
Proof. As and , and , and since . Let and , the value the code uses. The step is positive, and after line L8 the point is in . The gradient of is , so line L9 is the exact update. Along ,
Since and , , so the change is at most .
Termination. The code runs the loop at most max_iter times and raises an error if it has not stopped, so it never returns a wrong answer. By Lemma 3 the value of strictly decreases, so no state repeats. Finite termination for of SMO with the maximal violating pair on problems of this form, a convex quadratic with box constraints and one linear equality, is the result of Keerthi and Gilbert (2002) for the SVM classifier dual.
Lemma 4 (the stop gives an epsilon optimal point). If the loop stops with , then .
Proof. Let and , so . Each with is in , so , and each with is in , so . With , we get . By convexity, . Take optimal.
If the loop stops because is empty, all , so and has the single point , which is optimal.
Lemma 5 (the radius). At the stop with , let be the value of line L10 and . Then , and if , and if .
Proof. A free coordinate is in , so its gradient is in , and so is their mean. Otherwise . By Lemma 1, . If , , so . If , , so .
When , the code sets , so and every point is on or outside the sphere, which is the condition for coordinates at the bound.
Corollary (counts). At the stop, at most training points have , and at least have .
Proof. A point with has by Lemma 5, and such points give . If coordinates are positive, , so .
Theorem (the hard ball). Let and let be the squared radius of the smallest ball in feature space that holds all . At the stop with and , the ball with center and squared radius satisfies and . Also .
Proof. First, . Every . A coordinate with satisfies by Lemma 5. A coordinate with exists only if and . Then the center is and . Any other point has , so by Lemma 5, and again .
Weak duality. For any center and any ,
where the minimum is at the weighted mean . So for all , and .
The other direction. With , , by the same identity. Each with has by Lemma 5, so . The ball at with squared radius holds all points, so
using , which holds because is the minimum, and weak duality at the end.
Equality. Let be a minimizer. Then , since otherwise the step of Lemma 3 would lower below . So the argument above applies to with and any between the two values, and it gives . With weak duality, .
By Lemmas 2 to 5, the corollary and the theorem, the procedure returns a feasible within of the optimum, a radius consistent with the optimality conditions up to , and for the minimum enclosing ball up to in squared radius.
Complexity
The cost is in the real-RAM model.
- Kernel matrix. Line L1 takes time and space.
- Each step. Lines L5 and L9 scan coordinates, so steps take time.
- The radius. Line L11 computes once, in time.
- Prediction. takes time, with the number of support vectors.
Properties
- The role of . With for , at most a fraction of the training points are outside and at least a fraction are support vectors. This is the same counting argument as for the -property of the one-class SVM.
- Same as the one-class SVM for the Gaussian kernel. When is a constant, the term is constant on the feasible set, and the dual becomes , the dual of the one-class SVM with . The two methods then give the same and the same boundary (Scholkopf et al. 2001, Section 3).
- Different for other kernels. With the linear kernel the boundary is a sphere in the input space, which the one-class SVM, a half space, cannot give.
- Unique center. The optimal value is unique, and the center is unique in feature space, even when the weights are not.
Variants and improvements
- Negative examples. Tax and Duin add known anomalies with a constraint that they lie outside the sphere. This gives weights of the opposite sign in the dual.
- Other kernels. The Gaussian kernel is the usual choice; its width sets how closely the boundary follows the data, and it is chosen by a heuristic, such as a target fraction of support vectors.
- Large data. Core set methods for the minimum enclosing ball find a approximation from a subset of size , independent of and .
- Deep SVDD. A neural network maps the data so that normal points lie close to a fixed center, trained by minimizing the mean squared distance to that center.
When to use it
Use it when the normal class is compact and one region describes it well, and when a distance to a center is a natural score. With the Gaussian kernel it is the same detector as the one-class SVM, so the choice between the two is a matter of the parameterization. With the linear kernel it flags points far from a center that a few outliers in the training set do not move much.
Pitfalls
- below . The constraint with needs . Check this before line L2.
- The radius from a bound point. If line L10 reads from a point with , which is outside, or , which is inside, the radius is too large or too small. Take it from the free points.
- The wrong step. The quadratic term of the SVDD dual is , not . Line L7 divides by . With the one-class SVM step, which divides by the expression without the factor 2, an unclipped step jumps to the mirror point on the other side of the minimum, does not go down, and the loop may never stop.
- Outliers still pull the center. A training point outside the sphere keeps the weight and moves the center toward itself, as the example shows. If the training data hold many anomalies, the description is biased. Use a smaller only as far as the bound on the outside fraction allows.
- Unscaled features. Distances in the input space set both the linear and the Gaussian kernel. Scale the features first.
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/support-vector-data-description/. The authors are listed in prov/1GJAG1.jsonl.
import math
from dataclasses import dataclass
from typing import Callable, Sequence
Point = Sequence[float]
Kernel = Callable[[Point, Point], float]
def linear_kernel(a: Point, b: Point) -> float:
"""k(a, b) = <a, b>. Cost: O(d)."""
return sum(u * v for u, v in zip(a, b))
def gaussian_kernel(gamma: float) -> Kernel:
"""Return k(a, b) = exp(-gamma |a - b|^2). Cost of one call: O(d)."""
def k(a: Point, b: Point) -> float:
return math.exp(-gamma * sum((u - v) ** 2 for u, v in zip(a, b)))
return k
@dataclass(frozen=True)
class SVDD:
points: tuple[tuple[float, ...], ...]
alpha: tuple[float, ...]
radius2: float
center_norm2: float
kernel: Kernel
def dual_objective(alpha: Sequence[float], k: Sequence[Sequence[float]]) -> float:
"""f(alpha) = alpha^T K alpha - sum_i alpha_i K_ii, the negated SVDD dual. Cost: O(n^2)."""
n = len(alpha)
quad = sum(alpha[i] * k[i][j] * alpha[j] for i in range(n) for j in range(n))
return quad - sum(alpha[i] * k[i][i] for i in range(n))
def fit_svdd(x: Sequence[Point], c: float, kernel: Kernel, eps: float = 1e-9, max_iter: int = 1_000_000) -> SVDD:
"""Train the support vector data description of Tax and Duin.
Solves min a^T K a - sum_i a_i K_ii subject to 0 <= a_i <= c and sum a_i = 1
by SMO on the maximal violating pair; on return the value is within eps of the
optimum. With c >= 1 this is the smallest enclosing ball in feature space.
Precondition: n >= 1, c >= 1/n, eps > 0, kernel positive semidefinite.
Cost: Theta(n^2 d) for the kernel matrix, O(n) per iteration, O(n^2) space.
"""
n = len(x)
if n < 1 or c * n < 1.0 - 1e-12 or eps <= 0.0:
raise ValueError("need n >= 1, c >= 1/n and eps > 0")
k = [[kernel(x[i], x[j]) for j in range(n)] for i in range(n)] # @line L1
a = [0.0] * n
full = min(n, int(1.0 / c + 1e-12))
for r in range(full): # @line L2
a[r] = min(c, 1.0)
if full < n:
a[full] = min(c, max(0.0, 1.0 - full * c))
g = [2.0 * sum(k[r][s] * a[s] for s in range(n)) - k[r][r] for r in range(n)] # @line L3
lo_g = up = 0.0
for _ in range(max_iter): # @line L4
up_set = [r for r in range(n) if a[r] < c]
if not up_set:
break
i = min(up_set, key=lambda r: g[r]) # @line L5
j = max((r for r in range(n) if a[r] > 0.0), 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) / (2.0 * 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] += 2.0 * t * (k[r][i] - k[r][j])
else:
raise RuntimeError("no convergence within max_iter")
quad = sum(a[r] * k[r][s] * a[s] for r in range(n) for s in range(n))
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)):
level = max(g) # c = 1/n: every point is at the bound, so on or outside the sphere
elif free:
level = sum(free) / len(free) # @line L10
else:
level = (lo_g + up) / 2.0
# The squared distance of x_r to the center is K_rr - 2 (K a)_r + a^T K a = quad - g_r.
radius2 = quad - level
pts = tuple(tuple(float(v) for v in p) for p in x)
return SVDD(pts, tuple(a), radius2, quad, kernel) # @line L11
def distance2(model: SVDD, z: Point) -> float:
"""Squared feature space distance of z to the center. Cost: O(n d)."""
cross = sum(ai * model.kernel(xi, z) for ai, xi in zip(model.alpha, model.points) if ai > 0.0)
return model.kernel(z, z) - 2.0 * cross + model.center_norm2
def is_outside(model: SVDD, z: Point) -> bool:
"""True when z lies outside the ball, the SVDD rule for flagging. Cost: O(n d)."""
return distance2(model, z) > model.radius2
test_support_vector_data_description.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/support-vector-data-description/. The authors are listed in prov/1GJAG1.jsonl.
import itertools
import math
import random
import pytest
from support_vector_data_description import (
distance2,
dual_objective,
fit_svdd,
gaussian_kernel,
is_outside,
linear_kernel,
)
EPS = 1e-10
def brute_force_meb(pts):
"""Smallest enclosing circle in the plane: the best circle through 2 or 3 of the points."""
best = math.inf
cands = []
for p, q in itertools.combinations(pts, 2):
cands.append(((p[0] + q[0]) / 2, (p[1] + q[1]) / 2))
for p, q, r in itertools.combinations(pts, 3):
ax, ay = p
bx, by = q
cx, cy = r
den = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by))
if abs(den) < 1e-12:
continue
ux = ((ax * ax + ay * ay) * (by - cy) + (bx * bx + by * by) * (cy - ay) + (cx * cx + cy * cy) * (ay - by)) / den
uy = ((ax * ax + ay * ay) * (cx - bx) + (bx * bx + by * by) * (ax - cx) + (cx * cx + cy * cy) * (bx - ax)) / den
cands.append((ux, uy))
for ctr in cands:
best = min(best, max((p[0] - ctr[0]) ** 2 + (p[1] - ctr[1]) ** 2 for p in pts))
return best
def kernel_matrix(x, kern):
return [[kern(p, q) for q in x] for p in x]
def check_conditions(model, x, c, eps):
n = len(x)
a = model.alpha
assert all(0.0 <= ai <= c for ai in a)
assert math.isclose(sum(a), 1.0, abs_tol=1e-12)
for ai, p in zip(a, x):
d2 = distance2(model, p)
if ai < c:
assert d2 <= model.radius2 + eps + 1e-9
if ai > 0.0:
assert d2 >= model.radius2 - eps - 1e-9
outside = sum(distance2(model, p) > model.radius2 + eps + 1e-9 for p in x)
assert outside <= 1.0 / c + 1e-9
assert sum(ai > 0.0 for ai in a) >= 1.0 / c - 1e-9 or c >= 1.0
def test_example() -> None:
x = [(0.0, 0.0), (2.0, 0.0), (0.0, 2.0), (2.0, 2.0), (1.0, 1.0), (6.0, 1.0)]
hard = fit_svdd(x, 1.0, linear_kernel, eps=EPS)
# The circle through (0, 0), (0, 2) and (6, 1) has center (35/12, 1) and squared radius 1369/144.
assert math.isclose(hard.radius2, 1369 / 144, abs_tol=1e-8)
assert all(distance2(hard, p) <= hard.radius2 + 1e-8 for p in x)
assert fit_svdd(x, 0.5, linear_kernel, eps=EPS).alpha == pytest.approx(hard.alpha, abs=1e-6)
soft = fit_svdd(x, 0.25, linear_kernel, eps=EPS)
check_conditions(soft, x, 0.25, EPS)
assert soft.alpha == pytest.approx([0.25, 0.125, 0.25, 0.125, 0.0, 0.25], abs=1e-6)
assert math.isclose(soft.radius2, 1.0, abs_tol=1e-6)
assert [is_outside(soft, p) for p in x] == [True, False, True, False, False, True]
def test_edges() -> None:
one = fit_svdd([(3.0, 4.0)], 1.0, linear_kernel)
assert one.alpha == (1.0,) and abs(one.radius2) < 1e-12
two = fit_svdd([(0.0,), (4.0,)], 1.0, linear_kernel, eps=EPS)
assert math.isclose(two.radius2, 4.0, abs_tol=1e-8)
every = fit_svdd([(0.0,), (1.0,), (5.0,)], 1 / 3, linear_kernel)
assert all(math.isclose(ai, 1 / 3) for ai in every.alpha)
with pytest.raises(ValueError):
fit_svdd([(0.0,), (1.0,)], 0.4, linear_kernel)
with pytest.raises(ValueError):
fit_svdd([], 1.0, linear_kernel)
def test_hard_ball_against_brute_force() -> None:
rng = random.Random(77)
for _ in range(500):
n = rng.randint(2, 7)
x = [(rng.uniform(-5, 5), rng.uniform(-5, 5)) for _ in range(n)]
model = fit_svdd(x, 1.0, linear_kernel, eps=EPS)
want = brute_force_meb(x)
# With c = 1 the dual optimum equals the squared radius of the smallest enclosing ball.
assert abs(-dual_objective(model.alpha, kernel_matrix(x, linear_kernel)) - want) <= 1e-8
assert abs(model.radius2 - want) <= 1e-6 * max(1.0, want)
assert all(distance2(model, p) <= want + 1e-6 for p in x)
def test_soft_and_gaussian_conditions() -> None:
rng = random.Random(5)
for _ in range(150):
n = rng.randint(2, 8)
x = [(rng.uniform(-3, 3), rng.uniform(-3, 3)) for _ in range(n)]
c = max(1.0 / n, rng.choice([1.0, 0.5, 0.3, 1.0 / n, rng.uniform(1.0 / n, 1.0)]))
kern = rng.choice([linear_kernel, gaussian_kernel(0.5), gaussian_kernel(2.0)])
model = fit_svdd(x, c, kern, eps=EPS)
check_conditions(model, x, c, EPS)
def test_outlier_is_flagged_with_gaussian_kernel() -> None:
rng = random.Random(11)
x = [(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(80)]
c = 1.0 / (0.1 * len(x))
model = fit_svdd(x, c, gaussian_kernel(0.1), eps=1e-7)
outside = sum(is_outside(model, p) for p in x)
assert outside <= 0.1 * len(x)
assert is_outside(model, (5.0, 5.0))
assert not is_outside(model, (0.0, 0.0))
History
Tax and Duin introduced the support vector domain description in Pattern Recognition Letters in 1999 and the full support vector data description in Machine Learning in 2004, with outliers in the training set, negative examples and kernels. At the same time, Scholkopf and coauthors developed the one-class SVM and showed in 2001 that the two coincide for kernels with constant . Later work studied fast solvers through the minimum enclosing ball and, from 2018, deep versions that learn the feature map.
References
- David M. J. Tax and Robert P. W. Duin, Support vector data description, Machine Learning 54(1), pages 45 to 66, 2004, the primal problem with slack, the dual, the radius from a support vector on the boundary, the test for new objects, and the Gaussian kernel
- David M. J. Tax and Robert P. W. Duin, Support vector domain description, Pattern Recognition Letters 20(11 to 13), pages 1191 to 1199, 1999, the first version of the method
- 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 ball form and its equivalence with the one-class SVM for kernels with constant k(x, x))
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 1GJAG1 Edit this page History Report an error Markdown