One-class SVM: a region is not a diagnosis
单类 SVM
Solve a scalar one-class SVM exactly and distinguish support vectors, boundary points and outside readings.
one-class-svmA boundary needs a reference population
A collection of accepted sensor readings can answer a useful question: does a new reading resemble that reference set? It cannot, by itself, tell us whether an unusual reading means a broken sensor, a new operating mode or a recording mistake.
One-class SVM fits a decision region without requiring examples from a second class. In novelty detection, the reference data are intended to represent normal operation; outlier detection instead allows the training set itself to contain anomalies. That distinction changes how we collect and evaluate the data. The scikit-learn guide separates these settings.
We will solve an intentionally restrictive case: a linear model with one numerical feature. For readings 1, 2, 3, 6 and parameter ν = 3/8, its optimum puts 1 outside, 2 on the boundary, and 3, 6 inside. Two records are support vectors. Neither the outside fraction, 1/4, nor the support fraction, 1/2, equals ν.
The restriction makes every coefficient auditable. It also makes a failure easy to see: the fitted region accepts 100. A half-line cannot describe “close to the usual readings” on both sides.
The origin, the offset and two different counts
Let φ map an input to feature space, let n be the number of training records, and set C = 1/(νn), with 0 < ν ≤ 1. The original formulation balances a small weight norm, slack penalties and an offset away from the feature-space origin:
A positive decision value lies inside; zero is the boundary. A positive-semidefinite kernel supplies feature-space inner products without constructing φ. The dual coefficients obey a capped sum constraint:
These are the primal, dual and decision rule in Schölkopf and colleagues’ 2001 paper, §3. The origin belongs to feature space; it is not a labeled negative training example. A support vector is a training record with α greater than zero.
For our scalar linear kernel, k(x,z) = xz and w is the weighted sum of the readings. Let L and U be its smallest and largest feasible values. Fill the coefficient cap on the smallest readings to obtain L, and on the largest to obtain U. An exchange argument proves optimality: moving available mass from a larger reading to a smaller one cannot increase the mean. Because the feasible coefficients form a convex compact set, their scalar means fill the entire interval. Therefore:
If the interval crosses zero, a convex combination of its two endpoint coefficient vectors produces w = 0. This is an exact optimizer, not a search over a numerical grid. The final equality is a primal–dual certificate: feasibility and complementary slackness make both objectives equal. Here D denotes the dual maximization objective; it has the opposite sign from the minimized quadratic above.
To choose ρ, write vᵢ = wxᵢ. Complementary slackness gives three cases:
A free coefficient fixes ρ. Without one, capped records give a lower bound and zero coefficients give an upper bound. Our program chooses their midpoint. At ν = 1 all coefficients equal 1/n, the upper bound is absent, and it chooses the lower endpoint. Different valid offsets can define different decision regions when the optimum is not unique.
A strict outside point has positive slack and hence αᵢ = C. Counting these coefficients, and separately counting all positive coefficients, proves:
This proof applies to the exact primal–dual solutions considered here, including our zero-offset degeneracy. The paper’s Proposition 3 states its ν-property under ρ ≠ 0 and adds separate distribution/kernel assumptions for an asymptotic equality. We do not import that asymptotic claim into a finite dataset with ties. Boundary points need not all be support vectors, and a capped coefficient need not be strictly outside.
An exact scalar solver
Run this complete Python 3.10+ program using only the standard library. Inputs are integers or Fraction values in a list or tuple; booleans and floating-point inputs are rejected. Training must be nonempty. predict expects an unmodified model returned by fit, and accepts an empty query list. It returns outside, boundary or inside rather than hiding zero behind a binary convention.
Equal readings use original row index as their coefficient allocation priority. Training takes O(n log(n+1)) arithmetic/comparison operations and O(n+1) stored values. This includes two sorts and all returned audit arrays. Predicting q points takes O(q+1) operations and output space. Fraction arithmetic is exact, but its bit cost increases with numerator and denominator lengths; these are not constant-time bit-complexity bounds. There is no kernel matrix or general quadratic-program solver in this implementation.
from fractions import Fraction as F
def rational(value):
if isinstance(value, bool) or not isinstance(value, (int, F)):
raise ValueError('use integers or Fraction values')
return F(value)
def vector(values):
if not isinstance(values, (tuple, list)):
raise ValueError('expected a list or tuple')
return tuple(rational(v) for v in values)
def fit(values, nu):
x, nu = vector(values), rational(nu)
if not x or not 0 < nu <= 1:
raise ValueError('need nonempty data and 0 < nu <= 1')
n = len(x)
cap = 1 / (nu * n)
def extreme(reverse):
order = sorted(range(n), key=lambda i: ((-x[i] if reverse else x[i]), i))
alpha, remaining = [F(0)] * n, F(1)
for i in order:
alpha[i] = min(cap, remaining)
remaining -= alpha[i]
return tuple(alpha), sum((a * v for a, v in zip(alpha, x)), F(0))
low, left = extreme(False)
high, right = extreme(True)
if left >= 0:
alpha = low
elif right <= 0:
alpha = high
else:
t = -left / (right - left)
alpha = tuple((1 - t) * a + t * b for a, b in zip(low, high))
w = sum((a * v for a, v in zip(alpha, x)), F(0))
values_at_x = tuple(w * v for v in x)
capped = [v for a, v in zip(alpha, values_at_x) if a == cap]
unused = [v for a, v in zip(alpha, values_at_x) if a == 0]
free = [v for a, v in zip(alpha, values_at_x) if 0 < a < cap]
lower = max(capped) if capped else None
upper = min(unused) if unused else None
if free:
rho = free[0]
elif upper is None:
rho = lower
else:
rho = (lower + upper) / 2
margins = tuple(v - rho for v in values_at_x)
slacks = tuple(max(F(0), -v) for v in margins)
primal = w * w / 2 + cap * sum(slacks, F(0)) - rho
dual = -w * w / 2
return {'x': x, 'nu': nu, 'cap': cap, 'alpha': alpha,
'w_interval': (left, right), 'w': w, 'rho': rho,
'rho_bounds': (lower, upper), 'margins': margins,
'slacks': slacks, 'primal': primal, 'dual': dual,
'gap': primal - dual,
'support': tuple(i for i, a in enumerate(alpha) if a > 0),
'outside': tuple(i for i, v in enumerate(margins) if v < 0)}
def predict(model, queries):
queries = vector(queries)
margins = tuple(model['w'] * q - model['rho'] for q in queries)
return tuple((v, 'outside' if v < 0 else 'inside' if v > 0 else 'boundary')
for v in margins)
if __name__ == '__main__':
model = fit((1, 2, 3, 6), F(3, 8))
print('alpha:', tuple(map(str, model['alpha'])))
print('w, rho:', str(model['w']), str(model['rho']))
print('training margins:', tuple(map(str, model['margins'])))
print('support, outside:', model['support'], model['outside'])
print('primal, dual, gap:', *(str(model[k]) for k in ('primal', 'dual', 'gap')))
print('query 100:', tuple((str(v), state) for v, state in predict(model, (100,))))
tied = fit((2, 2, 2), F(1, 3))
print('tied support, margins:', tied['support'], tuple(map(str, tied['margins'])))
zero = fit((-1, 1), F(1, 2))
print('zero model:', str(zero['w']), str(zero['rho']), predict(zero, (0,)))
Actual output:
alpha: ('2/3', '1/3', '0', '0')
w, rho: 4/3 8/3
training margins: ('-4/3', '0', '4/3', '16/3')
support, outside: (0, 1) (0,)
primal, dual, gap: -8/9 -8/9 0
query 100: (('392/3', 'inside'),)
tied support, margins: (0,) ('0', '0', '0')
zero model: 0 0 ((Fraction(0, 1), 'boundary'),)
For the main case, C = 2/3. The first coefficient reaches the cap; the second is free and sets ρ = w·2 = 8/3. The strict outside point has slack 4/3. Substituting these values into the primal gives −8/9, exactly the dual value. The negative objective is expected because the primal contains −ρ.
The test companion also solves the primal independently. For each sign of w, a minimizing offset can be chosen at a hinge breakpoint ρ = wxⱼ. Substitution leaves a quadratic on a half-line, whose minimum is analytic. Comparing those candidates checks the interval solver without reproducing its coefficient allocation.
What a margin does not establish
The returned decision value is an unnormalized margin, not an anomaly probability. When w is nonzero, dividing by its norm gives signed distance to the feature-space hyperplane. When w = 0, that geometric distance is undefined. In (-1, 1) with ν = 1/2, the program returns w = ρ = 0: every possible scalar query is on the boundary.
Changing units or centering is part of model design. In particular, translating the scalar data changes their position relative to the origin and need not preserve this linear model’s decisions. General kernels change the available regions. The fixed OneClassSVM API provides kernel choices, ν and numerical optimization controls; the scalar solver here does not reproduce that library. ν constrains training counts at an optimum, not the fraction of future equipment faults or alerts.
A usable evaluation needs an independently collected reference period and a later or otherwise separated test period. Fit preprocessing on the training reference only. Where possible, review both alerts and non-alerts against actual operating records, and measure missed events as well as false alarms. If a new operating mode is legitimate, it may call for updating the reference rather than celebrating an “anomaly detected.” The acceptable region is a modeling choice, not a diagnosis.
Check the boundary yourself
1. Why do the two observed fractions differ from ν?
Answer: For (1, 2, 3, 6) at ν = 3/8, α is (2/3, 1/3, 0, 0) and the margins are (-4/3, 0, 4/3, 16/3). There is one strict outside point and two support vectors, so 1/4 ≤ 3/8 ≤ 1/2. The bounds do not require equality.
2. Recover an offset when there is no free support vector.
Answer: Set ν = 1/2 on the same readings. The coefficients become (1/2, 1/2, 0, 0) and w = 3/2. Capped points require ρ ≥ 3; zero coefficients require ρ ≤ 9/2. The program chooses 15/4. Any offset in that interval is optimal, although endpoint choices move a training point onto the boundary.
3. Must every boundary point have a positive coefficient?
Answer: No. On (2, 2, 2) at ν = 1/3, the selected coefficients are (1, 0, 0), w = 2 and ρ = 4. All three margins are zero, but only row 0 is a support vector. Other coefficient allocations may also be optimal; the deterministic row priority selects one certificate.
4. Does accepting 100 show that the exact optimizer failed?
Answer: No. The main model accepts x ≥ 2, so 100 has margin 392/3 and is inside. The certificate proves that the chosen linear objective was optimized. It does not prove that a half-line captures the intended notion of a normal sensor reading. A different feature map or model must be justified and evaluated against that task.
From a region estimate to a working detector
The 2001 support-estimation paper connects kernel geometry, regularization and a controllable training boundary. Its optimization section develops pairwise coefficient updates for the general kernel problem; our one-dimensional interval argument is a separate teaching shortcut. Its statistical theory addresses more than merely counting the points returned by an optimizer.
The OneClassSVM documentation makes a useful operational distinction: score_samples is the unshifted score, while decision_function subtracts the learned offset. Changing a threshold changes the alert rule; changing a kernel changes the geometry available to the fit.
Continue with support vector machines and the kernel trick for the broader optimization framework. Compare Isolation Forest and local outlier factor to see how different definitions of unusualness can disagree on the same observation.
Make a prediction, then check
Four readings at nu = 3/8 produce one strict outside point and two support vectors. Is this inconsistent with the nu bounds?
Learning objectives
- Derive the capped dual coefficients and distinguish support, boundary and strict outside records.
- Verify an exact scalar optimum with feasibility, complementarity and equal primal–dual objectives.
- Separate training nu bounds from future alert rates and domain-specific anomaly meaning.
Prerequisites & connections
Explore related knowledge →References
- Estimating the Support of a High-Dimensional Distribution
Bernhard Schölkopf; John C. Platt; John Shawe-Taylor; Alex J. Smola; Robert C. Williamson · 2001 - OneClassSVM — scikit-learn 1.7.2
scikit-learn developers - Novelty and Outlier Detection — scikit-learn 1.7.2
scikit-learn developers
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Eight tests pass. Fifty small scalar fits are independently solved in the primal: enumerate hinge breakpoints rho = w*x_j separately on positive and negative half-lines, analytically minimize each scalar quadratic, and compare optimal weight/objective. This does not repeat the implemented sorted capped-simplex allocation. Every fit also passes complete feasibility, stationarity, complementarity, primal-dual equality and both finite count bounds.
- Verified the four-row exact coefficients, margins, -8/9 certificate and accepted query 100; no-free-support offset interval [3,9/2], nu=1 unbounded-above offset range, duplicate rows with zero-coefficient boundary points, origin-crossing zero model, translation counterexample, eighteen permutation/nu configurations, empty queries and no input/model mutation. Rejected six invalid training forms, seven invalid nu values and four invalid query forms. An initially ineffective translation-test query was corrected to compare corresponding queries 1 and 3; no algorithm correction was needed.
- Full bilingual original prose, eight stdout lines, identical complete standard-library Python, five matching displayed formulas, six stable anchors and four answered exercises. Strict MDX/KaTeX with actual React HTML passes; all mathematical annotations agree and no literal emphasis markers remain. Pinned Humanizer guidance applied. Future links use verified catalogue IDs. Costs include audit arrays and empty predictions, with exact-rational bit costs qualified.
- AI author technical checks only; review remains written pending independent cross-review. The implementation is an exact one-dimensional linear special case, not a general kernel solver or library replica. No human review, library training, empirical accuracy study, browser acceptance or whole-site build.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Estimating the Support of a High-Dimensional Distribution · Actually read author-hosted PDF, 29 pages: section 3, printed 1446–1448 (PDF pages 4–6), equations 3.4–3.12, dual coefficient support definition, nonnegative boundary sign convention and nu=1 coefficients; section 4, printed 1449–1451, pairwise optimization; section 5 Proposition 3, printed 1453, explicitly rho not equal to zero, with separate continuous-distribution/analytic nonconstant-kernel assumptions for the asymptotic statement; Appendix B printed 1465, complementarity and nu proof sketch. Our finite coefficient-count proof covers our rho=0 case independently and does not attribute that expanded statement to Proposition 3. Google Research official publication record additionally confirms author order and Neural Computation 13 (2001), pages 1443–1471. No benchmark, full visual audit, or historical priority beyond the journal version claimed.
- OneClassSVM — scikit-learn 1.7.2 · Actually opened fixed 1.7 API rendered 1.7.2. Read lines 623–650 for support estimation and kernels, 664–665 for nu range and training error/support bounds, 688–705 for coefficients/intercept, 731–734 for decision_function = score_samples - offset_, 781–784 and 922–941 for score direction. Article deliberately calls the raw output an unnormalized margin, not a calibrated probability or automatically normalized distance. No sklearn execution.
- Novelty and Outlier Detection — scikit-learn 1.7.2 · Actually opened fixed guide rendered 1.7.2 and read lines 69–94 for reference-cleanliness versus training contamination, and 111–128 for OneClassSVM context. Its loose statement equating nu with new-observation outside probability is not adopted as a finite guarantee. The reused source identity and URL match the existing catalogue source; only relevant reference-sample distinctions are cited here.
- Estimating the Support of a High-Dimensional Distribution · Actually opened the author-hosted 29-page journal paper. Read the title/authors and Neural Computation 13, 1443–1471 (2001) header; section 3, printed 1446–1448, primal equation 3.4, capped-simplex dual 3.11, support definition, free-coefficient offset 3.12 and sign-at-zero footnote. Read Proposition 3 on printed 1453, including rho != 0 and its separate independent continuous-distribution/analytic nonconstant-kernel asymptotic conditions, and Appendix B proof sketch on printed 1465. The article’s direct finite coefficient-count proof correctly handles its rho=0 special case without attributing a stronger theorem to the paper. Extracted text only; no full-paper or visual audit.
- OneClassSVM — scikit-learn 1.7.2 · Actually read the exact fixed API rendered 1.7.2: lines 620–665, kernels, nu and its training-count interpretation; 688–705 coefficients/intercept; 731–734 raw score minus offset; 781–784 and 922–941 score direction and raw scores. The article correctly qualifies unnormalized margins and does not promise calibrated probabilities or API numerical equivalence.
- Novelty and Outlier Detection — scikit-learn 1.7.2 · Actually read the exact fixed guide rendered 1.7.2, lines 69–94 for reference cleanliness, novelty versus contaminated-training outlier detection and score threshold conventions; 111–128 for OneClassSVM and the loose future-outside-probability wording. The article avoids importing that wording as a finite generalization guarantee. No library training.
Related topics