Algorithm Search⌘K

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.

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
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 ν∈(0,1]\nu \in (0, 1] controls how tight the region is. Scholkopf, Platt, Shawe-Taylor, Smola and Williamson (2001) proved that ν\nu 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 ν\nu 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 x1,…,xn∈Rdx_1, \ldots, x_n \in \mathbb{R}^d, a parameter ν∈(0,1]\nu \in (0, 1], a kernel kk, and a tolerance ϵ>0\epsilon > 0. Here kk is the Gaussian kernel k(x,y)=e−γ∥x−y∥2k(x, y) = e^{-\gamma \lVert x - y \rVert^2} with γ>0\gamma > 0. Let Φ\Phi be a feature map with k(x,y)=⟨Φ(x),Φ(y)⟩k(x, y) = \langle \Phi(x), \Phi(y) \rangle. The primal problem is

min⁡w,ξ,ρ 12∥w∥2+1νn∑iξi−ρsubject to⟨w,Φ(xi)⟩≥ρ−ξi, ξi≥0.\min_{w, \xi, \rho} \ \tfrac12 \lVert w \rVert^2 + \frac{1}{\nu n} \sum_i \xi_i - \rho \quad \text{subject to} \quad \langle w, \Phi(x_i) \rangle \ge \rho - \xi_i, \ \xi_i \ge 0.

Its dual, with Kij=k(xi,xj)K_{ij} = k(x_i, x_j) and C=1/(νn)C = 1/(\nu n), is

min⁡a f(a)=12a⊤Kasubject to0≤ai≤C, ∑iai=1.\min_a \ f(a) = \tfrac12 a^\top K a \quad \text{subject to} \quad 0 \le a_i \le C, \ \textstyle\sum_i a_i = 1.

The output is a feasible aa with f(a)≤f∗+ϵf(a) \le f^* + \epsilon, where f∗f^* is the optimum, and an offset ρ\rho. The decision function is g(z)=∑iaik(xi,z)−ρg(z) = \sum_i a_i k(x_i, z) - \rho, and zz is flagged when g(z)<0g(z) < 0.

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 G=KaG = K a be the gradient of ff.

  1. ONE-CLASS-SVM(x[1..n], ν, k, ε)
  2. 1C ← 1 / (ν n); K[i][j] ← k(x_i, x_j) for all i, j
  3. 2a ← C on the first ⌊ν n⌋ coordinates, 1 - ⌊ν n⌋ C on the next one, 0 on the rest
  4. 3G ← K a
  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) / (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 + 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, ρ ▷ g(z) = Σ a_r k(x_r, z) - ρ

Line L2 is the start point of the paper: a fraction ν\nu of the weights at the upper bound and the rest of the mass on one more point, so that ∑a=1\sum a = 1. Line L5 picks the coordinate ii that can grow and has the smallest gradient, and the coordinate jj that can shrink and has the largest gradient. Moving weight tt from jj to ii changes ff by −t(Gj−Gi)+12t2(Kii+Kjj−2Kij)-t(G_j - G_i) + \tfrac12 t^2 (K_{ii} + K_{jj} - 2K_{ij}). Line L7 takes the minimizing tt and clips it to the box. Line L9 updates the gradient in O(n)O(n) time. The code replaces a denominator below 10−1210^{-12} by 10−1210^{-12}; the clip keeps the step inside the box.

Line L10 sets ρ\rho from the optimality conditions. At the optimum, Gr=ρG_r = \rho for each free coordinate, Gr≥ρG_r \ge \rho when ar=0a_r = 0 and Gr≤ρG_r \le \rho when ar=Ca_r = C. On the training set, g(xr)=Gr−ρg(x_r) = G_r - \rho. So points with ar=0a_r = 0 are inside the region, free points are on its boundary, and only points with ar=Ca_r = C can be outside.

Example

Take the six points 0,1,2,3,4,90, 1, 2, 3, 4, 9 on a line, γ=0.1\gamma = 0.1 and ν=0.6\nu = 0.6. Then C=1/3.6=0.2778C = 1/3.6 = 0.2778, and line L2 starts with a=(0.2778,0.2778,0.2778,0.1667,0,0)a = (0.2778, 0.2778, 0.2778, 0.1667, 0, 0). The solver stops at the values in the table, with ρ=0.5075\rho = 0.5075.

point ara_r status g(xr)g(x_r)
0 0.2778 at the bound CC -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 CC -0.0469
9 0.2778 at the bound CC -0.2047

The region where g≥0g \ge 0 is about the interval from 1 to 3; for example g(0.9)=−0.0040g(0.9) = -0.0040, g(2.5)>0g(2.5) > 0 and g(3.1)=−0.0035g(3.1) = -0.0035. The point 9 has the most negative value, and new points such as 6 (g=−0.1636g = -0.1636) are flagged. Three of six training points, a fraction 0.5, are outside, which is at most ν=0.6\nu = 0.6. Five of six are support vectors, a fraction 0.83, which is at least ν\nu. With a smaller ν\nu the bound CC 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 f∗f^*. The steps keep aa feasible: line L7 never moves aia_i above CC or aja_j below 0, and the sum does not change. Each step with Gj−Gi>ϵG_j - G_i > \epsilon lowers ff strictly. When the loop stops, let m=Gim = G_i and M=GjM = G_j with M−m≤ϵM - m \le \epsilon. For any feasible bb, convexity gives f(b)≥f(a)+G⊤(b−a)f(b) \ge f(a) + G^\top (b - a), and the sign pattern of b−ab - a gives G⊤(b−a)≥−(M−m)G^\top (b - a) \ge -(M - m). So f(a)≤f∗+ϵf(a) \le f^* + \epsilon. The same bound gives g(xr)≥−ϵg(x_r) \ge -\epsilon when ar<Ca_r < C and g(xr)≤ϵg(x_r) \le \epsilon when ar>0a_r > 0.

The ν\nu-property (Proposition 3 of the paper, which assumes ρ≠0\rho \ne 0) follows from the box. A training point with g(xr)<−ϵg(x_r) < -\epsilon has ar=Ca_r = C, and at most 1/C=νn1/C = \nu n coordinates can equal CC when they sum to 1. So at most a fraction ν\nu of the points are outside. A sum of 1 with terms at most CC needs at least νn\nu n nonzero terms, so at least a fraction ν\nu are support vectors. Part (iii) of the proposition says that both fractions tend to ν\nu as nn 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 ϵ>0\epsilon > 0 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. KK is the kernel matrix, positive semidefinite, C=1/(νn)C = 1/(\nu n) with 0<ν≤10 < \nu \le 1, and the feasible set is S={a:0≤ar≤C, ∑rar=1}S = \{a : 0 \le a_r \le C, \ \sum_r a_r = 1\}. It is not empty, because nC=1/ν≥1nC = 1/\nu \ge 1. The objective is f(a)=12a⊤Kaf(a) = \tfrac12 a^\top K a, a convex function, and SS is compact, so ff has a minimum f∗f^* on SS. Write U(a)={r:ar<C}U(a) = \{r : a_r < C\}, D(a)={r:ar>0}D(a) = \{r : a_r > 0\} and G=KaG = K a.

Lemma 1 (start point). The vector of line L2 is in SS.

Proof. Let q=⌊νn⌋q = \lfloor \nu n \rfloor. Then qC≤νnC=1q C \le \nu n C = 1, so the remainder 1−qC1 - qC is in [0,1][0, 1]. It is also less than CC, because q+1>νnq + 1 > \nu n gives (q+1)C>1(q + 1) C > 1. If q=nq = n there is no remainder, and nC=1nC = 1. The code clips the remainder to [0,C][0, C], which only matters for rounding. All entries are in [0,C][0, C] and they sum to 1. □\square

Lemma 2 (one step). Suppose M−m>ϵM - m > \epsilon at line L6, with m=Gim = G_i, M=GjM = G_j. Then lines L7 to L9 keep aa in SS, keep G=KaG = K a, and lower ff by at least 12t(M−m)>0\tfrac12 t (M - m) > 0.

Proof. Since i∈Ui \in U and j∈Dj \in D, C−ai>0C - a_i > 0 and aj>0a_j > 0. Also i≠ji \ne j, since i=ji = j would give M−m=0M - m = 0. 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 let τ=max⁡(η,10−12)≥η\tau = \max(\eta, 10^{-12}) \ge \eta be the value the code uses. The step t=min⁡((M−m)/τ,C−ai,aj)t = \min((M - m)/\tau, C - a_i, a_j) is positive. After line L8, ai≤Ca_i \le C, aj≥0a_j \ge 0, and the sum is unchanged, so a∈Sa \in S. Since K(a+t(ei−ej))=Ka+t(Kei−Kej)K(a + t(e_i - e_j)) = Ka + t(K e_i - K e_j), line L9 keeps G=KaG = Ka. Along the direction ei−eje_i - e_j,

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

Since t≤(M−m)/τt \le (M - m)/\tau and η≤τ\eta \le \tau, we have tη≤M−mt \eta \le M - m, so the change is at most −t(M−m)+12t(M−m)=−12t(M−m)<0-t(M - m) + \tfrac12 t (M - m) = -\tfrac12 t (M - m) < 0. □\square

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 ϵ>0\epsilon > 0 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 ff strictly decrease, so no state repeats.

Lemma 3 (the stop gives an epsilon optimal point). If the loop stops at line L6 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. Then ∑rδr=0\sum_r \delta_r = 0. If δr>0\delta_r > 0, then ar<br≤Ca_r < b_r \le C, so r∈Ur \in U and Gr≥mG_r \ge m. If δr<0\delta_r < 0, then ar>br≥0a_r > b_r \ge 0, so r∈Dr \in D and Gr≤MG_r \le M. Let P=∑δr>0δr=−∑δr<0δrP = \sum_{\delta_r > 0} \delta_r = -\sum_{\delta_r < 0} \delta_r. Then

G⊤δ≥mP−MP=−(M−m)P.G^\top \delta \ge m P - M P = -(M - m) P.

Also P≤∑δr>0br≤∑rbr=1P \le \sum_{\delta_r > 0} b_r \le \sum_r b_r = 1. So G⊤δ≥−(M−m)≥−ϵG^\top \delta \ge -(M - m) \ge -\epsilon. Because ff is convex and differentiable with gradient GG at aa, f(b)≥f(a)+G⊤δ≥f(a)−ϵf(b) \ge f(a) + G^\top \delta \ge f(a) - \epsilon. Taking bb optimal gives f∗≥f(a)−ϵf^* \ge f(a) - \epsilon. □\square

If instead the loop stops because UU is empty, then every ar=Ca_r = C, so nC=1nC = 1, ν=1\nu = 1, and S={(1/n,…,1/n)}S = \{(1/n, \ldots, 1/n)\} has one point, which is optimal.

Lemma 4 (the offset and the approximate KKT conditions). At the stop with M−m≤ϵM - m \le \epsilon, the value ρ\rho of line L10 is in [m,M][m, M]. For each training point, g(xr)=Gr−ρg(x_r) = G_r - \rho, and g(xr)≥−ϵg(x_r) \ge -\epsilon if ar<Ca_r < C, and g(xr)≤ϵg(x_r) \le \epsilon if ar>0a_r > 0.

Proof. A free coordinate is in both UU and DD, so its gradient is in [m,M][m, M], and so is a mean of such values. If there is no free coordinate, ρ=(m+M)/2∈[m,M]\rho = (m + M)/2 \in [m, M]. By definition g(xr)=∑sasKsr−ρ=Gr−ρg(x_r) = \sum_s a_s K_{sr} - \rho = G_r - \rho, using the symmetry of KK. If ar<Ca_r < C, then Gr≥m≥M−ϵ≥ρ−ϵG_r \ge m \ge M - \epsilon \ge \rho - \epsilon. If ar>0a_r > 0, then Gr≤M≤m+ϵ≤ρ+ϵG_r \le M \le m + \epsilon \le \rho + \epsilon. □\square

When ν=1\nu = 1, the code sets ρ=max⁡rGr\rho = \max_r G_r, so g(xr)≤0g(x_r) \le 0 for all rr, which is the condition for coordinates at the bound CC.

Theorem (the nu-property, finite form). At the stop, the number of training points with g(xr)<−ϵg(x_r) < -\epsilon is at most νn\nu n, and the number of support vectors, the points with ar>0a_r > 0, is at least νn\nu n.

Proof. By Lemma 4, a point with g(xr)<−ϵg(x_r) < -\epsilon cannot have ar<Ca_r < C, so ar=Ca_r = C. If pp coordinates equal CC, then pC≤∑rar=1p C \le \sum_r a_r = 1, so p≤1/C=νnp \le 1/C = \nu n. For the second part, if ss coordinates are positive, then 1=∑rar≤sC1 = \sum_r a_r \le s C, so s≥1/C=νns \ge 1/C = \nu n. □\square

With ϵ→0\epsilon \to 0 this is parts (i) and (ii) of Proposition 3 of Scholkopf et al. (2001), for the points with g(xr)<0g(x_r) < 0. By Lemmas 1 to 4 and the theorem, the procedure returns a feasible aa with f(a)≤f∗+ϵf(a) \le f^* + \epsilon, an offset that satisfies the optimality conditions up to ϵ\epsilon, and a decision function with the ν\nu-property. ■\blacksquare

Complexity

The cost is in the real-RAM model, with one unit for each arithmetic operation and each evaluation of exe^x.

  • 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 a step costs O(n)O(n), and rr steps cost O(rn)O(r n). There is no useful bound on rr in terms of nn alone.
  • Prediction. g(z)g(z) costs O(sd)O(s d), where ss is the number of support vectors, at least νn\nu n.
  • Large data. Solvers such as LIBSVM keep only a cache of kernel rows instead of all of KK, so the space is O(n)O(n) plus the cache.

Properties

  • The meaning of ν\nu. ν\nu 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 ρ≠0\rho \ne 0). This is the theorem above. The false alarm rate on new normal data is close to the training fraction only for large nn; 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 ff is strictly convex and the optimal aa is unique.
  • Same as a ball. For kernels with constant k(x,x)k(x, x), 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 ar=0a_r = 0, the inside points, do not enter gg. Only the support vectors are kept.
  • Kernel width. A large γ\gamma makes narrow bumps and a region that hugs each training point; a small γ\gamma makes a smooth region. Choosing γ\gamma without labeled anomalies is a heuristic.

Variants and improvements

  • Other kernels. Any positive definite kernel works. With a kernel whose k(x,x)k(x, x) is not constant, the method differs from the ball of SVDD.
  • Second order working sets. LIBSVM chooses jj by the largest decrease of ff 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.
  • ν=1\nu = 1. All weights equal 1/n1/n, and gg 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 ν\nu. 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 C=1/(νn)C = 1/(\nu n). If line L1 uses C=1/νC = 1/\nu, the box never binds, the ν\nu-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.
  • ρ\rho from a bound coordinate. If line L10 takes ρ\rho from a point at ar=Ca_r = C or ar=0a_r = 0, ρ\rho 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 ii among coordinates below CC and jj 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 ν\nu 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.

one_class_svm.pyI0RawGitHub
# 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 ν\nu-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

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

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
  • at least three sources
  • a scene preset for the example