One-Class SVM for novelty detection and anomaly detection.
Classes
One-Class Support Vector Machine for novelty and anomaly detection.
__init__( self, kernel: str = 'rbf', nu: float = 0.1, gamma: float | str = 'auto', degree: int = 3, coef0: float = 0.0, tol: float = 0.001, max_iter: int = 1000, )
Overview
The algorithm works by mapping the input data into a high-dimensional feature space (using a kernel) and finding the hyperplane that best separates the data from the origin with a maximum margin:
- Map data to high dimensions via the selected kernel (e.g., RBF)
- Solve an optimization problem to find a "frontier" encompassing the data
- New points are checked against this frontier
- Points falling outside the frontier are labeled as anomalies
Theory
The One-Class SVM solves the following optimization problem:
Subject to:
- w: Normal vector to the separating hyperplane
- \rho: Offset from the origin
- \nu (nu): Controls the trade-off between keeping data inside the frontier and the "smoothness" of the boundary
- \phi: Non-linear mapping to a higher-dimensional space (defined by the kernel)
- \xi_i: Slack variables allowing for points to lie outside the boundary
- Positive score → Normal point (inside the decision boundary)
- Negative score → Anomaly (outside the decision boundary)
Parameters
kernel
Kernel function used to map data to higher dimensions:
- •
"linear": Linear kernel - •
"rbf": Radial Basis Function (Gaussian) - •
"poly": Polynomial kernel - •
"sigmoid": Sigmoid kernel
nu
(0, 1]. Roughly corresponds to the expected contamination rate.
gamma
Kernel coefficient for RBF, polynomial, and sigmoid kernels:
- •
"auto": Uses1 / n_features - •
float: User-defined positive coefficient
degree
coef0
tol
max_iter
0 or a negative value for max(10000, 100 * n_samples), which is enough to reach tol on typical data.
Attributes
support_vectors_
dual_coef_
offset_
n_support_
support_
n_iter_
tol.
gamma_
n_features_in_
fit().
Notes
Solver: the \nu-formulation dual is solved by Sequential Minimal Optimization over the maximal-violating pair, the same working-set rule LIBSVM uses:
\nu acts through the box bound alone, which is what makes it an upper bound on the fraction of training points left outside the boundary and a lower bound on the support vector fraction. The iteration starts from a feasible point and is fully deterministic, so repeated fits on the same data give the same model without needing a seed.
Complexity:
- Training: O(n^2) per iteration bound by the kernel matrix, O(n^2) memory
- Prediction: O(n_{sv} \cdot p) where n_{sv} is the number of support vectors
- Novelty detection (training set contains only/mostly normal samples)
- High-dimensional data where non-linear boundaries are required
- Complex data distributions that can be captured with kernels
- When precise control over the "frontier" shape is needed via hyper-parameters
-
High sensitivity to hyper-parameters (especially
nuandgamma) - Poor scalability to very large datasets (cubic training time in worst case)
- Not natively robust to outliers in the training set (unlike robust covariance)
- Interpretation of results in high-dimensional kernel space is difficult
References
See Also
Basic usage for novelty detection:
>>> from tuiml.algorithms.anomaly import OneClassSVMDetector
>>> import numpy as np
>>>
>>> # Generate normal training data
>>> X_train = np.random.randn(100, 2)
>>>
>>> # Fit the model on normal data
>>> clf = OneClassSVMDetector(nu=0.1, kernel="rbf", gamma="auto")
>>> clf.fit(X_train)
>>>
>>> # Predict on new data (one normal, one anomaly)
>>> X_test = np.array([[0, 0], [10, 10]])
>>> predictions = clf.predict(X_test)
>>> print(predictions)
[ 1 -1]
>>>
>>> # Get decision function scores
>>> scores = clf.decision_function(X_test)
>>> print(scores.round(2))
[ 0.08 -0.09]
Methods
fit
(self, X: np.ndarray, _y: Optional[np.ndarray]=None) -> 'OneClassSVMDetector'
fit
(self, X: np.ndarray, _y: Optional[np.ndarray]=None) -> 'OneClassSVMDetector'
Fit the One-Class SVM model.
Parameters
X
_y
Returns
self