Algorithm Search⌘K

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.

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
Properties
deterministicnot exactofflineiterative
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 CC 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 x1,…,xn∈Rdx_1, \ldots, x_n \in \mathbb{R}^d, a kernel kk with feature map Φ\Phi, a penalty CC with C≥1/nC \ge 1/n, and a tolerance ϵ>0\epsilon > 0. The primal problem is

min⁡R,c,ξ R2+C∑iξisubject to∥Φ(xi)−c∥2≤R2+ξi, ξi≥0.\min_{R, c, \xi} \ R^2 + C \sum_i \xi_i \quad \text{subject to} \quad \lVert \Phi(x_i) - c \rVert^2 \le R^2 + \xi_i, \ \xi_i \ge 0.

With Kij=k(xi,xj)K_{ij} = k(x_i, x_j) its dual, written as a minimization, is

min⁡a f(a)=a⊤Ka−∑iaiKiisubject to0≤ai≤C, ∑iai=1.\min_a \ f(a) = a^\top K a - \sum_i a_i K_{ii} \quad \text{subject to} \quad 0 \le a_i \le C, \ \textstyle\sum_i a_i = 1.

The center is c=∑iaiΦ(xi)c = \sum_i a_i \Phi(x_i), and the squared distance of a point zz to it is

D(z)=k(z,z)−2∑iaik(xi,z)+a⊤Ka.D(z) = k(z, z) - 2 \sum_i a_i k(x_i, z) + a^\top K a.

The output is a feasible aa with f(a)≤f∗+ϵf(a) \le f^* + \epsilon and the squared radius R2R^2. A point zz is flagged when D(z)>R2D(z) > R^2. For C≥1C \ge 1 the bound never binds and the problem is the minimum enclosing ball of the points Φ(xi)\Phi(x_i). For C<1/nC < 1/n the constraints cannot hold.

The algorithm

The solver is sequential minimal optimization on the dual, as for the one-class SVM. Let G=2Ka−diag(K)G = 2 K a - \mathrm{diag}(K) be the gradient of ff. On the training points, D(xr)=a⊤Ka−GrD(x_r) = a^\top K a - G_r.

  1. SVDD(x[1..n], C, k, ε)
  2. 1K[i][j] ← k(x_i, x_j) for all i, j
  3. 2a ← C on the first ⌊1/C⌋ coordinates, 1 - ⌊1/C⌋ C on the next one, 0 on the rest
  4. 3G ← 2 K a - diag(K)
  5. 4loop
  6. 5i ← argmin of G_r over {r : a_r < C}; j ← argmax of G_r over {r : a_r > 0}
  7. 6if G_j - G_i ≤ ε then leave the loop
  8. 7t ← min((G_j - G_i) / (2 (K_ii + K_jj - 2 K_ij)), C - a_i, a_j)
  9. 8a_i ← a_i + t; a_j ← a_j - t
  10. 9G ← G + 2 t (K[·][i] - K[·][j])
  11. 10λ ← the mean of G_r over the free r (0 < a_r < C), or (G_i + G_j) / 2 if there are none
  12. 11return a, R² = aᵀ K a - λ ▷ flag z when D(z) > R²

Line L2 starts from a feasible point; for C≥1C \ge 1 it puts all the weight on the first point. Moving weight tt from jj to ii changes ff by −t(Gj−Gi)+t2(Kii+Kjj−2Kij)-t (G_j - G_i) + t^2 (K_{ii} + K_{jj} - 2K_{ij}), and line L7 takes the minimizing tt 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 D(xr)=R2D(x_r) = R^2, which is Gr=λG_r = \lambda. Points with ar=0a_r = 0 are inside or on the sphere, and points with ar=Ca_r = C are on or outside it.

Example

Take the six points (0,0)(0,0), (2,0)(2,0), (0,2)(0,2), (2,2)(2,2), (1,1)(1,1) and (6,1)(6,1) with the linear kernel k(x,y)=⟨x,y⟩k(x, y) = \langle x, y \rangle, so the ball is an ordinary disk.

CC nonzero weights center R2R^2 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 C=1C = 1 the result is the smallest disk that holds all six points: the circle through (0,0)(0,0), (0,2)(0,2) and (6,1)(6,1), with center (35/12,1)(35/12, 1) and R2=1369/144R^2 = 1369/144. The point (6,1)(6,1) makes it large. With C=0.5C = 0.5 no weight reaches the bound, so the disk does not change. With C=0.25C = 0.25 at most 1/C=41/C = 4 weights can be at the bound. The solution leaves three points outside and shrinks the disk to center (2,1)(2, 1) and radius 1, with (2,0)(2,0) and (2,2)(2,2) on the circle and (1,1)(1,1) on it as well. The center is still pulled toward (6,1)(6,1), because a point outside keeps the weight CC.

Correctness

The dual is a convex quadratic program over a compact set. As for the one-class SVM, each step keeps aa feasible and lowers ff strictly, and the stop test gives f(a)≤f∗+ϵf(a) \le f^* + \epsilon by convexity: for any feasible bb, G⊤(b−a)≥−(Gj−Gi)G^\top (b - a) \ge -(G_j - G_i). The same bound gives D(xr)≤R2+ϵD(x_r) \le R^2 + \epsilon when ar<Ca_r < C and D(xr)≥R2−ϵD(x_r) \ge R^2 - \epsilon when ar>0a_r > 0. So at most 1/C1/C training points are outside the sphere by more than ϵ\epsilon, and at least 1/C1/C have a positive weight. For C≥1C \ge 1 the sphere is within 2ϵ2\epsilon 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. KK is a positive semidefinite kernel matrix with feature map Φ\Phi, C≥1/nC \ge 1/n, and S={a:0≤ar≤C, ∑rar=1}S = \{a : 0 \le a_r \le C, \ \sum_r a_r = 1\}, which is not empty because nC≥1nC \ge 1. The objective f(a)=a⊤Ka−∑rarKrrf(a) = a^\top K a - \sum_r a_r K_{rr} is convex, and SS is compact, so ff has a minimum f∗f^* on SS. Write G=2Ka−diag(K)G = 2Ka - \mathrm{diag}(K), Q=a⊤KaQ = a^\top K a, c=∑rarΦ(xr)c = \sum_r a_r \Phi(x_r), U={r:ar<C}U = \{r : a_r < C\} and D={r:ar>0}D = \{r : a_r > 0\}.

Lemma 1 (distances). D(xr)=∥Φ(xr)−c∥2=Q−GrD(x_r) = \lVert \Phi(x_r) - c \rVert^2 = Q - G_r.

Proof. ∥Φ(xr)−c∥2=Krr−2(Ka)r+Q\lVert \Phi(x_r) - c \rVert^2 = K_{rr} - 2 (K a)_r + Q, and Gr=2(Ka)r−KrrG_r = 2 (Ka)_r - K_{rr}. □\square

Lemma 2 (start point). Line L2 gives a point of SS. With q=⌊1/C⌋q = \lfloor 1/C \rfloor ones at value CC (or one coordinate at 1 when C≥1C \ge 1), qC≤1qC \le 1 and the remainder 1−qC1 - qC is in [0,C)[0, C). If q=nq = n the remainder is 0. □\square

Lemma 3 (one step). If M−m>ϵM - m > \epsilon at line L6, with m=Gim = G_i and M=GjM = G_j, then lines L7 to L9 keep a∈Sa \in S, keep G=2Ka−diag(K)G = 2Ka - \mathrm{diag}(K), and lower ff by at least 12t(M−m)>0\tfrac12 t (M - m) > 0.

Proof. As i∈Ui \in U and j∈Dj \in D, C−ai>0C - a_i > 0 and aj>0a_j > 0, and i≠ji \ne j since M>mM > m. Let η=Kii+Kjj−2Kij=∥Φ(xi)−Φ(xj)∥2≥0\eta = K_{ii} + K_{jj} - 2K_{ij} = \lVert \Phi(x_i) - \Phi(x_j) \rVert^2 \ge 0 and τ=max⁡(η,10−12)\tau = \max(\eta, 10^{-12}), the value the code uses. The step t=min⁡((M−m)/(2τ),C−ai,aj)t = \min((M - m)/(2\tau), C - a_i, a_j) is positive, and after line L8 the point is in SS. The gradient of a↦a⊤Kaa \mapsto a^\top K a is 2Ka2Ka, so line L9 is the exact update. Along ei−eje_i - e_j,

f(a+t(ei−ej))−f(a)=t(Gi−Gj)+t2η=−t(M−m)+t2η.f(a + t(e_i - e_j)) - f(a) = t (G_i - G_j) + t^2 \eta = -t (M - m) + t^2 \eta.

Since 2tτ≤M−m2 t \tau \le M - m and η≤τ\eta \le \tau, t2η≤12t(M−m)t^2 \eta \le \tfrac12 t (M - m), so the change is at most −12t(M−m)<0-\tfrac12 t (M - m) < 0. □\square

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 ff strictly decreases, so no state repeats. Finite termination for ϵ>0\epsilon > 0 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 M−m≤ϵM - m \le \epsilon, then f(a)≤f∗+ϵf(a) \le f^* + \epsilon.

Proof. Let b∈Sb \in S and δ=b−a\delta = b - a, so ∑rδr=0\sum_r \delta_r = 0. Each rr with δr>0\delta_r > 0 is in UU, so Gr≥mG_r \ge m, and each rr with δr<0\delta_r < 0 is in DD, so Gr≤MG_r \le M. With P=∑δr>0δr≤∑rbr=1P = \sum_{\delta_r > 0} \delta_r \le \sum_r b_r = 1, we get G⊤δ≥mP−MP≥−(M−m)≥−ϵG^\top \delta \ge mP - MP \ge -(M - m) \ge -\epsilon. By convexity, f(b)≥f(a)+G⊤δ≥f(a)−ϵf(b) \ge f(a) + G^\top \delta \ge f(a) - \epsilon. Take bb optimal. □\square

If the loop stops because UU is empty, all ar=Ca_r = C, so C=1/nC = 1/n and SS has the single point (1/n,…,1/n)(1/n, \ldots, 1/n), which is optimal.

Lemma 5 (the radius). At the stop with M−m≤ϵM - m \le \epsilon, let λ\lambda be the value of line L10 and R2=Q−λR^2 = Q - \lambda. Then λ∈[m,M]\lambda \in [m, M], and D(xr)≤R2+ϵD(x_r) \le R^2 + \epsilon if ar<Ca_r < C, and D(xr)≥R2−ϵD(x_r) \ge R^2 - \epsilon if ar>0a_r > 0.

Proof. A free coordinate is in U∩DU \cap D, so its gradient is in [m,M][m, M], and so is their mean. Otherwise λ=(m+M)/2\lambda = (m + M)/2. By Lemma 1, D(xr)=Q−GrD(x_r) = Q - G_r. If ar<Ca_r < C, Gr≥m≥λ−ϵG_r \ge m \ge \lambda - \epsilon, so D(xr)≤R2+ϵD(x_r) \le R^2 + \epsilon. If ar>0a_r > 0, Gr≤M≤λ+ϵG_r \le M \le \lambda + \epsilon, so D(xr)≥R2−ϵD(x_r) \ge R^2 - \epsilon. □\square

When C=1/nC = 1/n, the code sets λ=max⁡rGr\lambda = \max_r G_r, so R2=min⁡rD(xr)R^2 = \min_r D(x_r) 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 1/C1/C training points have D(xr)>R2+ϵD(x_r) > R^2 + \epsilon, and at least min⁡(n,1/C)\min(n, 1/C) have ar>0a_r > 0.

Proof. A point with D(xr)>R2+ϵD(x_r) > R^2 + \epsilon has ar=Ca_r = C by Lemma 5, and pp such points give pC≤1pC \le 1. If ss coordinates are positive, 1=∑ar≤sC1 = \sum a_r \le sC, so s≥1/Cs \ge 1/C. □\square

Theorem (the hard ball). Let C≥1C \ge 1 and let R∗2R_*^2 be the squared radius of the smallest ball in feature space that holds all Φ(xr)\Phi(x_r). At the stop with M−m≤ϵM - m \le \epsilon and n≥2n \ge 2, the ball with center cc and squared radius R2R^2 satisfies max⁡rD(xr)≤R2+ϵ\max_r D(x_r) \le R^2 + \epsilon and R∗2≤R2+ϵ≤R∗2+2ϵR_*^2 \le R^2 + \epsilon \le R_*^2 + 2\epsilon. Also −f∗=R∗2-f^* = R_*^2.

Proof. First, max⁡rD(xr)≤R2+ϵ\max_r D(x_r) \le R^2 + \epsilon. Every ar≤1≤Ca_r \le 1 \le C. A coordinate with ar<Ca_r < C satisfies D(xr)≤R2+ϵD(x_r) \le R^2 + \epsilon by Lemma 5. A coordinate with ar=Ca_r = C exists only if C=1C = 1 and a=era = e_r. Then the center is c=Φ(xr)c = \Phi(x_r) and D(xr)=0D(x_r) = 0. Any other point ss has as=0<Ca_s = 0 < C, so 0≤D(xs)≤R2+ϵ0 \le D(x_s) \le R^2 + \epsilon by Lemma 5, and again D(xr)=0≤R2+ϵD(x_r) = 0 \le R^2 + \epsilon.

Weak duality. For any center uu and any b∈Sb \in S,

max⁡r∥Φ(xr)−u∥2≥∑rbr∥Φ(xr)−u∥2≥min⁡v∑rbr∥Φ(xr)−v∥2=∑rbrKrr−b⊤Kb=−f(b),\max_r \lVert \Phi(x_r) - u \rVert^2 \ge \sum_r b_r \lVert \Phi(x_r) - u \rVert^2 \ge \min_v \sum_r b_r \lVert \Phi(x_r) - v \rVert^2 = \sum_r b_r K_{rr} - b^\top K b = -f(b),

where the minimum is at the weighted mean v=∑rbrΦ(xr)v = \sum_r b_r \Phi(x_r). So R∗2≥−f(b)R_*^2 \ge -f(b) for all b∈Sb \in S, and R∗2≥−f∗R_*^2 \ge -f^*.

The other direction. With u=cu = c, −f(a)=∑rarD(xr)-f(a) = \sum_r a_r D(x_r), by the same identity. Each rr with ar>0a_r > 0 has D(xr)≥R2−ϵD(x_r) \ge R^2 - \epsilon by Lemma 5, so −f(a)≥R2−ϵ-f(a) \ge R^2 - \epsilon. The ball at cc with squared radius max⁡rD(xr)\max_r D(x_r) holds all points, so

R∗2≤max⁡rD(xr)≤R2+ϵ≤−f(a)+2ϵ≤−f∗+2ϵ≤R∗2+2ϵ,R_*^2 \le \max_r D(x_r) \le R^2 + \epsilon \le -f(a) + 2\epsilon \le -f^* + 2\epsilon \le R_*^2 + 2\epsilon,

using −f(a)≤−f∗-f(a) \le -f^*, which holds because f∗f^* is the minimum, and weak duality at the end.

Equality. Let a∗a^* be a minimizer. Then max⁡r∈D(a∗)Gr≤min⁡r∈U(a∗)Gr\max_{r \in D(a^*)} G_r \le \min_{r \in U(a^*)} G_r, since otherwise the step of Lemma 3 would lower ff below f∗f^*. So the argument above applies to a∗a^* with ϵ=0\epsilon = 0 and any λ\lambda between the two values, and it gives R∗2≤−f∗R_*^2 \le -f^*. With weak duality, −f∗=R∗2-f^* = R_*^2. □\square

By Lemmas 2 to 5, the corollary and the theorem, the procedure returns a feasible aa within ϵ\epsilon of the optimum, a radius consistent with the optimality conditions up to ϵ\epsilon, and for C≥1C \ge 1 the minimum enclosing ball up to 2ϵ2\epsilon in squared radius. ■\blacksquare

Complexity

The cost is in the real-RAM model.

  • Kernel matrix. Line L1 takes Θ(n2d)\Theta(n^2 d) time and Θ(n2)\Theta(n^2) space.
  • Each step. Lines L5 and L9 scan nn coordinates, so rr steps take O(rn)O(r n) time.
  • The radius. Line L11 computes a⊤Kaa^\top K a once, in O(n2)O(n^2) time.
  • Prediction. D(z)D(z) takes O(sd)O(s d) time, with ss the number of support vectors.

Properties

  • The role of CC. With C=1/(νn)C = 1/(\nu n) for ν∈(0,1]\nu \in (0, 1], at most a fraction ν\nu of the training points are outside and at least a fraction ν\nu are support vectors. This is the same counting argument as for the ν\nu-property of the one-class SVM.
  • Same as the one-class SVM for the Gaussian kernel. When k(x,x)k(x, x) is a constant, the term ∑iaiKii\sum_i a_i K_{ii} is constant on the feasible set, and the dual becomes min⁡12a⊤Ka\min \tfrac12 a^\top K a, the dual of the one-class SVM with C=1/(νn)C = 1/(\nu n). The two methods then give the same aa 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 ∑iaiΦ(xi)\sum_i a_i \Phi(x_i) 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 (1+ϵ)(1 + \epsilon) approximation from a subset of size O(1/ϵ)O(1/\epsilon), independent of nn and dd.
  • 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

  • CC below 1/n1/n. The constraint ∑ai=1\sum a_i = 1 with ai≤Ca_i \le C needs C≥1/nC \ge 1/n. Check this before line L2.
  • The radius from a bound point. If line L10 reads R2R^2 from a point with ar=Ca_r = C, which is outside, or ar=0a_r = 0, 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 a⊤Kaa^\top K a, not 12a⊤Ka\tfrac12 a^\top K a. Line L7 divides by 2(Kii+Kjj−2Kij)2(K_{ii} + K_{jj} - 2K_{ij}). 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, ff does not go down, and the loop may never stop.
  • Outliers still pull the center. A training point outside the sphere keeps the weight CC and moves the center toward itself, as the example shows. If the training data hold many anomalies, the description is biased. Use a smaller CC 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.

support_vector_data_description.pyI0RawGitHub
# 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 k(x,x)k(x, x). Later work studied fast solvers through the minimum enclosing ball and, from 2018, deep versions that learn the feature map.

References

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example