This is the fourth post in the series on model-based outlier detection. The first post covered the basics and robust statistics, the second introduced Isolation Forest, and the third covered the Local Outlier Factor. In this post I shall discuss the One-Class SVM (OCSVM), which does not score points by distance or density at all. It learns a boundary around the normal data in a kernel-induced feature space, and anything outside the boundary is an outlier candidate.
I reuse the dataset from the LOF post, so the numbers are directly comparable. The summary first:
- OCSVM reaches a ROC AUC of 0.979 at
gamma=0.5andnu=0.05, against 1.000 for LOF, 0.978 for Isolation Forest and 0.925 for k-NN distance. - It catches all 3 global outliers but only 1 of the 4 local outliers in its top 7. Like Isolation Forest, it has no notion of "local density".
gammais the parameter that matters: AUC ranges from 0.735 to 0.994 across the values I tried, andnumostly sets the cutoff.- Scaling matters a lot: AUC goes from 0.887 to 0.990 once a badly scaled feature is standardised.
The idea
A support vector machine for classification separates two classes with a maximum-margin hyperplane. With only one class there is nothing to separate from, so Schölkopf et al. (2001) made a clever choice: map the data into a feature space with a kernel, and separate it from the origin with the largest possible margin.
Let \(\phi\) be the feature map, \(K(x, z) = \langle \phi(x), \phi(z) \rangle\) the kernel and \(n\) the number of training points. OCSVM solves
$$\min_{w,\,\xi,\,\rho}\;\; \frac{1}{2}\lVert w \rVert^2 \;+\; \frac{1}{\nu n}\sum_{i=1}^{n} \xi_i \;-\; \rho \quad \text{subject to} \quad \langle w, \phi(x_i) \rangle \ge \rho - \xi_i,\;\; \xi_i \ge 0 .$$
The slack \(\xi_i\) lets a point fall on the wrong side of the hyperplane at a cost. In the dual form the solution is a weighted sum over a few support vectors:
$$f(x) = \sum_{i} \alpha_i \, K(x_i, x) - \rho, \qquad \text{with } 0 \le \alpha_i \le \frac{1}{\nu n}.$$
The rule is: \(f(x) \ge 0\) means normal, and \(f(x) < 0\) means outlier. The set \(\{x : f(x) = 0\}\) is the boundary you see in the figures below.
With the RBF kernel, \(K(x, z) = \exp(-\gamma \lVert x - z \rVert^2)\), every mapped point has unit length, so the "hyperplane away from the origin" becomes a flexible region around the data in the original space.
What the two parameters do
- \(\nu\) (
nu) is an upper bound on the fraction of training points that end up outside the boundary, and a lower bound on the fraction of support vectors. It is the closest thing OCSVM has to a contamination rate. - \(\gamma\) (
gamma) is the inverse width of the RBF kernel. A small \(\gamma\) gives a smooth, almost elliptical boundary, and a large \(\gamma\) gives a boundary that hugs every training point.
Checking the formula against scikit-learn
I do not reimplement the quadratic solver, because that is a long detour. Instead, the code below rebuilds the decision function \(f(x)\) by hand from the fitted dual coefficients and support vectors, and verifies that it matches decision_function. This confirms the formula above is exactly what the library evaluates.
import numpy as np
from scipy.spatial.distance import cdist
from sklearn.svm import OneClassSVM
def rbf(A, B, gamma):
return np.exp(-gamma * cdist(A, B, "sqeuclidean"))
def ocsvm_scores(model, Xq, gamma):
"""f(x) = sum_i alpha_i K(sv_i, x) - rho, built from the fitted dual coefficients."""
K = rbf(Xq, model.support_vectors_, gamma)
return K @ model.dual_coef_.ravel() + model.intercept_[0]
The dataset
The dataset is the same as in the LOF post: a tight cluster (300 points), a loose cluster (100 points), 4 planted local outliers close to the tight cluster and 3 planted global outliers far from everything. I constructed it deliberately to illustrate the differences between methods, so on real data the gaps will usually be smaller.
rng = np.random.RandomState(7)
dense = rng.normal([0, 0], 0.4, size=(300, 2))
sparse = rng.normal([6, 6], 1.6, size=(100, 2))
local_out = np.array([[1.8, 0.2], [-0.3, 1.9], [-1.6, -1.2], [0.6, -1.9]])
global_out = np.array([[-5.0, 8.0], [12.0, -3.0], [10.0, 12.0]])
X = np.vstack([dense, sparse, local_out, global_out])
n_reg = len(dense) + len(sparse)
y = np.r_[np.zeros(n_reg), np.ones(len(local_out) + len(global_out))] # 1 = planted outlier
is_local = np.r_[np.zeros(n_reg), np.ones(len(local_out)), np.zeros(len(global_out))].astype(bool)
is_global = np.r_[np.zeros(n_reg + len(local_out)), np.ones(len(global_out))].astype(bool)
n_planted = int(y.sum())
gamma0, nu0 = 0.5, 0.05
m = OneClassSVM(kernel="rbf", gamma=gamma0, nu=nu0).fit(X)
mine = ocsvm_scores(m, X, gamma0)
print("max |ours - sklearn| = %.2e" % np.abs(mine - m.decision_function(X)).max())
print("support vectors = %d of %d (nu*n = %.1f)" % (len(m.support_), len(X), nu0 * len(X)))
print("flagged = %d (%.1f%%)" % ((m.predict(X) == -1).sum(), 100 * (m.predict(X) == -1).mean()))
The output:
- The hand-built function matches scikit-learn. The largest difference is about \(7\times10^{-16}\), which is floating-point noise.
- 43 support vectors out of 407 points (10.6%). This is above the \(\nu\) lower bound of 5%, as the theory says it should be.
- 23 points are flagged (5.7%), close to \(\nu = 5\%\).
The boundary and the role of gamma
The next block fits OCSVM for six values of \(\gamma\) and draws the zero contour of the decision function.
import matplotlib.pyplot as plt
gx, gy = np.meshgrid(np.linspace(-7, 14, 300), np.linspace(-5, 14, 300))
grid = np.c_[gx.ravel(), gy.ravel()]
gammas = [0.01, 0.05, 0.1, 0.5, 2.0, 10.0]
fig, axes = plt.subplots(2, 3, figsize=(14, 8.5), sharex=True, sharey=True)
for ax, g in zip(axes.ravel(), gammas):
mm = OneClassSVM(kernel="rbf", gamma=g, nu=0.05).fit(X)
z = mm.decision_function(grid).reshape(gx.shape)
ax.contourf(gx, gy, z, levels=np.linspace(z.min(), 0, 8), cmap="Blues_r", alpha=0.55)
ax.contour(gx, gy, z, levels=[0], colors="k", linewidths=1.6) # the boundary
ax.scatter(X[y == 0, 0], X[y == 0, 1], s=9, c="lightgrey", edgecolors="none")
ax.scatter(X[is_local, 0], X[is_local, 1], s=55, c="tab:orange", edgecolors="k")
ax.scatter(X[is_global, 0], X[is_global, 1], s=55, c="tab:red", edgecolors="k")
ax.set_title(f"gamma = {g} (nu = 0.05)", fontsize=10)
plt.tight_layout()
plt.show()
Figure 1: the learned boundary (black line) for six values of gamma. Orange points are planted local outliers and red points are planted global outliers.
Reading the figure from the top-left:
- \(\gamma = 0.01\): one smooth, elliptical region. It is too coarse, so it swallows the area between the clusters and most of the local outliers sit inside it.
- \(\gamma = 0.05\) and \(0.1\): the region splits into a tight part and a loose part, which is about the right shape for this data.
- \(\gamma = 0.5\): the boundary tightens around the tight cluster and the local outliers sit right on it (2 of the 4 end up flagged at \(\nu = 0.05\)), but it is already wiggly in the loose cluster.
- \(\gamma = 2\) and \(10\): the boundary memorises individual points. Many regular points are flagged, and the planted outliers are no longer special.
Here are the numbers for the same sweep, using the negative decision function as the outlier score:
from sklearn.metrics import roc_auc_score
for g in gammas:
mm = OneClassSVM(kernel="rbf", gamma=g, nu=0.05).fit(X)
s = -mm.decision_function(X) # higher = more outlying
top = np.argsort(s)[::-1][:n_planted]
print("gamma=%-5g ROC AUC = %.3f | planted in top %d = %d | flagged = %d"
% (g, roc_auc_score(y, s), n_planted, y[top].sum(), (mm.predict(X) == -1).sum()))
| gamma | ROC AUC | Planted outliers in top 7 (of 7) | Flagged points |
|---|---|---|---|
| 0.01 | 0.764 | 4 | 20 |
| 0.05 | 0.986 | 4 | 19 |
| 0.1 | 0.994 | 5 | 21 |
| 0.5 | 0.979 | 4 | 23 |
| 2 | 0.852 | 0 | 47 |
| 10 | 0.735 | 0 | 140 |
The sweet spot is a moderate \(\gamma\) between 0.05 and 0.5, and the damage at both ends is large. One caveat: I picked these values knowing the answer. On real data you have no labels, so \(\gamma\) has to be chosen from domain knowledge, stability across values, or the default heuristic gamma="scale" (which uses \(1 / (d \cdot \operatorname{Var}(X))\)) applied to standardised data.
Figure 2: ROC AUC against gamma at nu = 0.05. The dashed line is LOF at k = 20.
The role of nu
Now keep \(\gamma = 0.5\) and vary \(\nu\).
for nu in [0.05, 0.10, 0.20, 0.30]:
mm = OneClassSVM(kernel="rbf", gamma=0.5, nu=nu).fit(X)
pred = mm.predict(X) == -1
print("nu=%.2f | flagged = %.1f%% | support vectors = %.1f%% | planted caught = %d/%d | false alarms = %d"
% (nu, 100 * pred.mean(), 100 * len(mm.support_) / len(X),
(pred & (y == 1)).sum(), n_planted, (pred & (y == 0)).sum()))
| nu | Flagged | Support vectors | Planted caught (of 7) | False alarms |
|---|---|---|---|---|
| 0.05 | 5.7% | 10.6% | 5 | 18 |
| 0.10 | 10.3% | 13.3% | 7 | 35 |
| 0.20 | 20.1% | 22.1% | 7 | 75 |
| 0.30 | 29.7% | 31.2% | 7 | 114 |
From \(\nu = 0.05\) upwards, the share of flagged points tracks \(\nu\) closely, and the share of support vectors is always above it, as the theory predicts. Raising \(\nu\) catches all 7 planted points at \(\nu = 0.10\), but each extra step costs many false alarms: 35 at 0.10 and 75 at 0.20. So \(\nu\) is an alarm-budget knob, and you should choose it from the cost of a false alarm, as in the Isolation Forest post.
Figure 3: the boundary and flagged points for nu = 0.05, 0.10 and 0.20. Green are flagged planted outliers, blue crosses are flagged regular points and red squares are planted outliers that were missed.
A pitfall: very small nu
I also tried \(\nu = 0.01\) and \(0.02\), and the results are worth a warning. At \(\gamma = 0.5\) the decision function is almost exactly zero for many points, and predict then depends on solver tolerance rather than on the data:
| nu | tol | d < 0 | d < −1e−6 | |d| < 1e−6 |
|---|---|---|---|---|
| 0.01 | 1e−3 | 29 | 29 | 0 |
| 0.01 | 1e−8 | 25 | 0 | 43 |
| 0.02 | 1e−3 | 27 | 27 | 0 |
| 0.02 | 1e−8 | 24 | 0 | 43 |
With the default tolerance, 29 points are flagged at \(\nu = 0.01\), which breaks the \(\nu\) upper bound of about 4 points. With a much tighter tolerance, none of them is clearly negative, and 43 points sit within \(10^{-6}\) of the boundary. The practical rule is do not use the sign of the decision function when \(\nu\) is tiny. Rank the points by the score and choose the cutoff yourself, for example the top 1% by \(-f(x)\).
OCSVM against the earlier methods
Now the same comparison as in the LOF post, with OCSVM added.
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor, NearestNeighbors
k = 20
lof = -LocalOutlierFactor(n_neighbors=k).fit(X).negative_outlier_factor_
knn_dist = NearestNeighbors(n_neighbors=k + 1).fit(X).kneighbors(X)[0][:, k]
iso = -IsolationForest(random_state=0).fit(X).score_samples(X)
oc = -OneClassSVM(kernel="rbf", gamma=0.5, nu=0.05).fit(X).decision_function(X)
scores = {"k-NN distance": knn_dist, "Isolation Forest": iso, "LOF (k=20)": lof, "One-Class SVM (RBF)": oc}
for name, s in scores.items():
top = np.argsort(s)[::-1][:n_planted]
print(f"{name:20s} ROC AUC = {roc_auc_score(y, s):.3f} | top {n_planted}: "
f"{int(is_local[top].sum())}/{is_local.sum()} local, {int(is_global[top].sum())}/{is_global.sum()} global")
| Method | ROC AUC | Local outliers in top 7 (of 4) | Global outliers in top 7 (of 3) |
|---|---|---|---|
| k-NN distance | 0.925 | 0 | 3 |
| Isolation Forest | 0.978 | 1 | 3 |
| LOF (k = 20) | 1.000 | 4 | 3 |
| One-Class SVM (RBF) | 0.979 | 1 | 3 |
Figure 4: the 7 highest-scoring points under each method. Green are planted outliers and blue crosses are regular points.
OCSVM lands next to Isolation Forest: all 3 global outliers, 1 local outlier, and the remaining slots go to regular points at the edge of the loose cluster. The reason is structural. An RBF kernel has one width \(\gamma\) for the whole space, so it cannot be tight enough for the cluster with a standard deviation of 0.4 and loose enough for the cluster with 1.6 at the same time. Figure 1 shows the compromise at every value of \(\gamma\). LOF avoids this because every point is compared with its own neighbourhood.
Feature scaling is not optional
Because the RBF kernel is built on Euclidean distances, a feature with a large range dominates. To see this, multiply the second coordinate by 100 and compare the unscaled data with the standardised data.
from sklearn.preprocessing import StandardScaler
Xbad = X.copy()
Xbad[:, 1] *= 100.0 # one feature on a 100x larger scale
for label, data in [("unscaled, x2 * 100", Xbad), ("standardised, x2 * 100", StandardScaler().fit_transform(Xbad))]:
mm = OneClassSVM(kernel="rbf", gamma="scale", nu=0.05).fit(data)
print("%-24s ROC AUC = %.3f" % (label, roc_auc_score(y, -mm.decision_function(data))))
The unscaled version gives an AUC of 0.887 and the standardised one gives 0.990. In a real project, put a StandardScaler and the OneClassSVM in one Pipeline, so that the scaler is fitted on training data only.
Novelty detection
OCSVM is most natural as a novelty detector: you train on data you believe is clean, and then score new observations. Unlike LocalOutlierFactor, there is no special flag, since OneClassSVM always supports predict and decision_function on new points.
X_clean = np.vstack([dense, sparse]) # training data assumed clean
nov = OneClassSVM(kernel="rbf", gamma=0.5, nu=0.05).fit(X_clean)
X_new = np.array([[0.1, -0.1], # typical point in the dense cluster
[6.5, 5.0], # typical point in the sparse cluster
[1.7, 0.1], # just outside the dense cluster
[9.0, -4.0]]) # far from everything
print("predict :", nov.predict(X_new)) # +1 inlier, -1 outlier
print("decision:", np.round(nov.decision_function(X_new), 3))
The output is predict: [ 1 1 -1 -1] and decision: [ 0.274 0.002 -0.391 -1.478]. The point just outside the tight cluster is rejected (−0.391), and so is the distant one (−1.478). Note that the typical point in the loose cluster scores only 0.002, which is barely above the boundary. A sign-based decision on such a point is fragile, which is the same message as the small-\(\nu\) pitfall above.
Practical notes
- Scale your features, as shown above. This matters more for OCSVM than for tree-based methods.
- Tune \(\gamma\) before \(\nu\). The shape of the boundary comes from \(\gamma\), and \(\nu\) mainly moves the cutoff. Try several values of \(\gamma\) and prefer settings where the flagged points stay the same.
- Treat the score as a ranking, and choose the cutoff from the cost of false alarms. Do not rely on
predictwhen \(\nu\) is very small. - Cost: training is roughly quadratic or worse in the number of points. For hundreds of thousands of rows, use a subsample, or switch to
SGDOneClassSVM(a linear model trained with stochastic gradient descent, usually combined with a kernel approximation such asNystroem) or to Isolation Forest. - Contaminated training data pulls the boundary outward. OCSVM tolerates a small fraction through \(\nu\), but a clean training set always helps.
- No single winner. On this dataset LOF is best because the density varies, but OCSVM is a good choice when you have a clean reference set and want a smooth, compact decision rule to deploy.
Conclusion
In this post I discussed how OCSVM learns a boundary around normal data, verified the decision function against scikit-learn, and showed how \(\gamma\) controls the shape of the boundary while \(\nu\) controls the alarm budget. On the dataset from the LOF post it scored a ROC AUC of 0.979, level with Isolation Forest and behind LOF, because a single kernel width cannot adapt to clusters of different density. In the next post I shall discuss autoencoders and PCA reconstruction error, which score a point by how badly a compressed model can rebuild it.
References:
- B. Schölkopf, J. C. Platt, J. Shawe-Taylor, A. J. Smola and R. C. Williamson, "Estimating the Support of a High-Dimensional Distribution", Neural Computation, 13(7), 2001.
- scikit-learn documentation:
sklearn.svm.OneClassSVM.
The code in this post was tested with Python 3 and scikit-learn 1.9.1.




No comments:
Post a Comment