Monday, 30 November 2026

Autoencoders and PCA reconstruction error (Part 5)

This is the fifth post in the series on model-based outlier detection. The earlier posts covered the basics and robust statistics, Isolation Forest, the Local Outlier Factor and the One-Class SVM. In this post I shall discuss a different idea: compress the data into a few numbers, rebuild it, and score each point by how badly the rebuild fails. The compressor can be PCA, or a neural-network autoencoder. Normal points share the structure that the compressor learned, so they are rebuilt well. A point that breaks the structure is not.

The summary first:

  • PCA reconstruction error finds one kind of outlier perfectly and the other not at all. On a 10-feature dataset it separates the 6 off-subspace outliers from regular points with an AUC of 1.000, and the 4 extreme in-subspace points with an AUC of only 0.558. Hotelling's \(T^2\) does the reverse (0.711 and 1.000).
  • The number of components matters. The off-subspace AUC is 1.000 at the true dimension (k = 3), but 0.900 at k = 1 and 0.959 at k = 8.
  • On a curved structure, PCA fails and an autoencoder works. Reconstruction error from a 1-component PCA gives an AUC of 0.469, which is worse than chance, while a 1-unit-bottleneck autoencoder gives 0.998 (median 1.000 over 8 seeds).
  • Training details decide the result. The same autoencoder scored a median AUC of 0.634 with the adam optimiser (range 0.405 to 0.998) and 1.000 with lbfgs (minimum 0.983).

The idea

Take a point \(x\), encode it into \(k\) numbers, decode it back to \(\hat{x}\), and measure the reconstruction error:

$$\text{score}(x) = \lVert x - \hat{x} \rVert^2 .$$

A large error means the point does not fit the structure the model learned from the data. For PCA with \(k\) components, \(W_k\) the matrix of the top \(k\) principal directions and \(\mu\) the mean, the rebuild is

$$\hat{x} = \mu + W_k W_k^{\top}(x - \mu),$$

which is the projection of \(x\) onto a \(k\)-dimensional flat subspace. An autoencoder is the nonlinear version: an encoder network \(f\) squeezes \(x\) through a narrow bottleneck and a decoder network \(g\) rebuilds it, so \(\hat{x} = g(f(x))\). It is trained to minimise the average reconstruction error on the training data. A linear autoencoder spans the same subspace as PCA, so what the neural network adds is the ability to learn curved structures.

Two kinds of outlier: \(T^2\) and \(Q\)

PCA splits every point into a part inside the signal subspace and a leftover part. If \(t_j\) is the score of the point on component \(j\) and \(\lambda_j\) is that component's variance, then two statistics from process monitoring are useful:

$$T^2 = \sum_{j \le k} \frac{t_j^2}{\lambda_j}, \qquad Q = \sum_{j > k} t_j^2 .$$

  • \(T^2\) (Hotelling) measures how far the point is within the model, scaled by the variance of each component. It is large for a point that is extreme but consistent with the correlations.
  • \(Q\) (also called SPE) is exactly the squared reconstruction error. It is large for a point that breaks the correlations, even if every feature is within its normal range.

The ordinary Mahalanobis distance is the same sum taken over all \(d\) components, so \(\text{Mahalanobis}^2 = T^2 + \sum_{j>k} t_j^2/\lambda_j\). It weights the leftover components by \(1/\lambda_j\), which makes it very sensitive to small deviations in directions where the data hardly varies.

Checking the formula against scikit-learn

As in the earlier posts, I first build the score from the definition and compare it with the library.

import numpy as np
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

def recon_error(model, X, is_pca):
    rec = model.inverse_transform(model.transform(X)) if is_pca else model.predict(X)
    return ((X - rec) ** 2).sum(axis=1)

# from-scratch PCA reconstruction error, via the SVD
k = 3
mu = Xs.mean(axis=0)
_, S, Vt = np.linalg.svd(Xs - mu, full_matrices=False)
Wk = Vt[:k].T                                          # top-k principal directions
rec_mine = mu + (Xs - mu) @ Wk @ Wk.T
Q_mine = ((Xs - rec_mine) ** 2).sum(axis=1)

pca = PCA(n_components=k).fit(Xs)
Q_sk = recon_error(pca, Xs, True)
print("max |ours - sklearn| in Q = %.2e" % np.abs(Q_mine - Q_sk).max())

(Xs is the standardised dataset defined in the next section.) The largest difference is about \(5\times10^{-15}\), so the formula is exactly what inverse_transform computes. The same kind of check works for the \(T^2\) and Mahalanobis identity above: the Mahalanobis distance from the covariance matrix and the sum of the squared whitened PCA scores agree to \(9\times10^{-13}\).

Dataset A: 10 features, 3 hidden factors

The first dataset has 1000 regular points. Each has 10 features, but they are generated from only 3 latent factors (standard deviations 3, 2 and 1) plus noise of 0.3, so the features are strongly correlated. On top of that I plant two kinds of outlier:

  • 6 off-subspace outliers. Normal latent values, plus a push of length 2.5 out of the signal subspace. Each feature stays within a normal range, but the correlations between features are broken.
  • 4 in-subspace extremes. Very large values of one factor (4.5 standard deviations along each of the first two factors), so they are far away, but they obey the correlations.

As in the earlier posts, I constructed this dataset to illustrate the point, so on real data the gaps will usually be smaller.

rng = np.random.RandomState(5)
d, k_true, n = 10, 3, 1000
Q_all, _ = np.linalg.qr(rng.normal(size=(d, d)))
W, W_perp = Q_all[:, :k_true], Q_all[:, k_true:]               # signal directions and their complement
Z = rng.normal(size=(n, k_true)) * np.array([3.0, 2.0, 1.0])   # latent factors
XA_reg = Z @ W.T + rng.normal(0, 0.3, size=(n, d))

# 6 off-subspace outliers: normal latent values plus a large push out of the signal subspace
Zo = rng.normal(size=(6, k_true)) * np.array([3.0, 2.0, 1.0])
push = rng.normal(size=(6, d - k_true)); push = 2.5 * push / np.linalg.norm(push, axis=1, keepdims=True)
out_off = Zo @ W.T + push @ W_perp.T + rng.normal(0, 0.3, size=(6, d))
# 4 in-subspace extreme outliers: far along a factor, but consistent with the correlations
Ze = np.array([[13.5, 0, 0], [-13.5, 0, 0], [0, 9.0, 0], [0, -9.0, 0]])
out_ext = Ze @ W.T + rng.normal(0, 0.3, size=(4, d))

XA = np.vstack([XA_reg, out_off, out_ext])
yA = np.r_[np.zeros(n), np.ones(10)]
off_mask = np.r_[np.zeros(n), np.ones(6), np.zeros(4)].astype(bool)
ext_mask = np.r_[np.zeros(n + 6), np.ones(4)].astype(bool)
Xs = StandardScaler().fit_transform(XA)

What does a feature-by-feature check see? The code below reports the largest absolute z-score over the 10 features for each point.

zmax = np.abs(Xs).max(axis=1)
print("off-subspace outliers:", np.round(zmax[off_mask], 2))
print("in-subspace extremes :", np.round(zmax[ext_mask], 2))
print("regular points: 99th percentile = %.2f, max = %.2f" % (np.percentile(zmax[yA == 0], 99), zmax[yA == 0].max()))
  • The 3 factors carry 93.8% of the variance (the first five components carry 53.9%, 31.9%, 8.1%, 1.9% and 1.1%), which is what the scree plot in Figure 1 shows.
  • The off-subspace outliers have a maximum |z| of 2.57, 2.44, 2.24, 3.08, 3.18 and 3.65. The largest value among regular points is 3.59, so none of them stands out feature by feature.
  • The extremes reach 4.34, 4.18, 3.87 and 4.01, which a simple z-score does notice.

\(T^2\) against \(Q\)

The next block computes both statistics for \(k = 3\) and the full Mahalanobis distance, and then draws Figure 1.

import matplotlib.pyplot as plt

T2 = ((pca.transform(Xs) ** 2) / pca.explained_variance_).sum(axis=1)     # variance inside the model
cov_inv = np.linalg.inv(np.cov(Xs, rowvar=False))
maha = np.einsum("ij,jk,ik->i", Xs - mu, cov_inv, Xs - mu)                # all 10 components

reg = yA == 0
plt.scatter(T2[reg], Q_sk[reg], s=9, c="lightgrey", label="regular")
plt.scatter(T2[off_mask], Q_sk[off_mask], s=70, c="tab:orange", edgecolors="k", label="off-subspace outliers")
plt.scatter(T2[ext_mask], Q_sk[ext_mask], s=70, c="tab:red", edgecolors="k", label="in-subspace extremes")
plt.xscale("log"); plt.yscale("log")
plt.xlabel("Hotelling T2"); plt.ylabel("Q (reconstruction error)"); plt.legend(); plt.show()

Figure 1: left, the scree plot, where 3 components carry almost all the variance. Right, \(T^2\) against \(Q\) on log axes: the orange off-subspace outliers are high on the Q axis and the red extremes are far out on the \(T^2\) axis.

The two kinds of outlier are separated by the two axes. A method that uses only one of them will miss the other kind.

Ranking comparison on dataset A

The code below scores every point with seven methods (the autoencoder row comes from the helper defined in the next section, using the median-AUC seed of 5) and reports the ROC AUC against all 10 planted outliers, against the off-subspace ones only (plus the regular points), and against the extremes only. The autoencoder here is a small MLPRegressor with a 3-unit bottleneck (explained in the next section).

from sklearn.ensemble import IsolationForest
from sklearn.metrics import roc_auc_score
from sklearn.neighbors import LocalOutlierFactor
from sklearn.svm import OneClassSVM

lof = -LocalOutlierFactor(n_neighbors=20).fit(Xs).negative_outlier_factor_
iso = -IsolationForest(random_state=0).fit(Xs).score_samples(Xs)
ocs = -OneClassSVM(kernel="rbf", gamma="scale", nu=0.01).fit(Xs).decision_function(Xs)
scores = {"Max |z| (univariate)": zmax, "Mahalanobis (all 10)": maha, "Hotelling T2 (k=3)": T2,
          "PCA reconstruction Q (k=3)": Q_sk, "LOF (k=20)": lof, "Isolation Forest": iso, "One-Class SVM": ocs}

for name, s in scores.items():
    top = np.argsort(s)[::-1][:10]
    print("%-28s AUC all = %.3f | off-subspace only = %.3f | extreme only = %.3f | top 10: %d/6 off, %d/4 ext"
          % (name, roc_auc_score(yA, s),
             roc_auc_score(yA[~ext_mask], s[~ext_mask]), roc_auc_score(yA[~off_mask], s[~off_mask]),
             off_mask[top].sum(), ext_mask[top].sum()))
Method AUC, all 10 AUC, off-subspace (6) AUC, extremes (4) Top 10 contains
Max |z| (univariate) 0.975 0.959 1.000 1 off, 4 ext
Mahalanobis (all 10) 0.999 1.000 0.998 6 off, 2 ext
Hotelling \(T^2\) (k = 3) 0.827 0.711 1.000 0 off, 4 ext
PCA reconstruction \(Q\) (k = 3) 0.823 1.000 0.558 6 off, 0 ext
Autoencoder (16-3-16) 0.792 1.000 0.480 6 off, 0 ext
LOF (k = 20) 0.998 0.996 1.000 3 off, 4 ext
Isolation Forest 0.938 0.896 1.000 0 off, 4 ext
One-Class SVM 0.982 0.975 0.994 0 off, 2 ext

What the table says:

  1. \(Q\) and the autoencoder are specialists. Both find all 6 off-subspace outliers (AUC 1.000) and rank the extremes like ordinary points (0.558 and 0.480). A reconstruction score alone would give you a false sense of security about extreme but consistent points.
  2. \(T^2\) is the mirror image: perfect on the extremes, weak on the off-subspace points (0.711).
  3. Mahalanobis over all 10 components covers both (AUC 0.999), because it adds the leftover directions weighted by \(1/\lambda_j\). In practice, a common recipe is to monitor \(T^2\) and \(Q\) together and flag a point if either is large.
  4. The autoencoder adds nothing here. Its AUC against all 10 points (median of 5 seeds: 0.792, range 0.683 to 0.812) is close to PCA's 0.823, as expected for a dataset with linear structure. A neural network is not worth its cost when the structure is linear.
  5. LOF is again very strong (0.998), probably because the planted points are well separated from their neighbours.

Choosing the number of components

The score \(Q\) depends on \(k\). Too few components leave real structure in the residual, and too many let the model absorb the outliers.

for kk in range(1, 10):
    pk = PCA(kk).fit(Xs)
    q = recon_error(pk, Xs, True)
    top = np.argsort(q)[::-1][:10]
    print("k=%d: variance kept = %.1f%% | AUC (off-subspace vs regular) = %.3f | off-subspace in top 10 = %d/6"
          % (kk, 100 * pk.explained_variance_ratio_.sum(), roc_auc_score(yA[~ext_mask], q[~ext_mask]), off_mask[top].sum()))
k Variance kept AUC (off-subspace vs regular) Off-subspace in top 10 (of 6)
1 53.9% 0.900 0
2 85.7% 0.996 5
3 93.8% 1.000 6
4 95.8% 0.997 5
5 96.9% 0.986 5
6 97.8% 0.986 4
7 98.6% 0.979 4
8 99.2% 0.959 4
9 99.6% 0.988 4

Figure 2: the off-subspace AUC (blue) and the share of the 6 off-subspace outliers found in the top 10 (orange dashed) against the number of components k.

The best result is at the true dimension, k = 3, which the scree plot points to as well. Above that, the extra components start to model the leftover noise and the quality declines slowly (the top-10 recall falls from 6 to 4). Note that the AUC at k = 9 (0.988) is slightly higher than at k = 8 (0.959). With only 6 planted points the curve is noisy, so do not read the small bumps. The practical rule is to pick \(k\) from the scree plot or from the reconstruction error on held-out data, and to check that the flagged points stay the same for a few neighbouring values.

Dataset B: when the structure is curved

PCA can only describe flat subspaces. To see an autoencoder earn its keep, take 600 points on a noisy curve in 2-D (a parabola with noise of 0.05) and plant 6 outliers at distance 0.6 to 0.7 from the curve. All of them lie inside the range of the data, so no univariate check can see them.

rng = np.random.RandomState(11)
t = rng.uniform(-1.6, 1.6, 600)
arc = np.c_[t, 0.9 * t ** 2 - 1.0] + rng.normal(0, 0.05, (600, 2))
tb = np.array([-1.2, -0.6, 0.0, 0.5, 1.0, 1.3])
offb = np.array([0.7, -0.7, 0.6, -0.6, 0.7, 0.6])
outB = np.c_[tb, 0.9 * tb ** 2 - 1.0 + offb]                                 # 0.6-0.7 away from the curve
XB = np.vstack([arc, outB])
yB = np.r_[np.zeros(600), np.ones(6)]
XBs = StandardScaler().fit_transform(XB)

q_pca = recon_error(PCA(1).fit(XBs), XBs, True)
print("PCA(1)  ROC AUC = %.3f | planted in top 6 = %d/6" % (roc_auc_score(yB, q_pca), np.isin(np.argsort(q_pca)[::-1][:6], np.where(yB == 1)[0]).sum()))

The 1-component PCA gives a ROC AUC of 0.469 and 0 of 6 planted points in the top 6. It is worse than random, because the straight line misses the whole curve, and the points that are farthest from the line are simply the regular points at one end of the curve (the cluster of blue crosses in the bottom-left panel of Figure 3).

Now the autoencoder. I use scikit-learn's MLPRegressor trained to reproduce its own input, with tanh units and hidden layers of 16, 1 and 16 units. The single middle unit is the bottleneck: the network has to describe every point by one number, which is exactly the right dimension for a curve.

from sklearn.neural_network import MLPRegressor

def autoencoder(X, hidden, seed=0, solver="lbfgs"):
    kw = {"learning_rate_init": 0.01} if solver == "adam" else {}
    return MLPRegressor(hidden_layer_sizes=hidden, activation="tanh", solver=solver,
                        max_iter=4000, random_state=seed, **kw).fit(X, X)

ae = autoencoder(XBs, (16, 1, 16), seed=0)
q_ae = recon_error(ae, XBs, False)
print("autoencoder ROC AUC = %.3f" % roc_auc_score(yB, q_ae))

The autoencoder gets an AUC of 0.998, with 4 of the 6 planted points in the top 6.

Figure 3: top-left, the data. Top-right, the 1-component PCA line. Bottom-left, the 6 highest PCA errors, all on regular points at one end of the curve. Bottom-right, the autoencoder's output (black) follows the curve, and 4 of its 6 highest errors are planted outliers (green).

Two details in the bottom-right panel are worth noting. First, the 2 planted outliers that are missed are the ones near the ends of the curve, which are closest to it. Second, the learned curve has a small kink near \(x_1 \approx 0.9\) for this seed, and that kink pushes 2 regular points (blue crosses) into the top 6. A neural network does not give a perfectly smooth curve, and that is the cost of flexibility.

The result depends on the training details

A neural-network detector has more moving parts than the earlier methods, so I checked how stable the result is. Here are 8 random seeds with two optimisers, on the same data and the same architecture:

for solver in ["adam", "lbfgs"]:
    a = []
    for seed in range(8):
        e = recon_error(autoencoder(XBs, (16, 1, 16), seed, solver), XBs, False)
        a.append(roc_auc_score(yB, e))
    print("%-6s AUC per seed = %s | median = %.3f | min = %.3f" % (solver, np.round(a, 3), np.median(a), np.min(a)))
Optimiser AUC for seeds 0 to 7 Median Minimum
adam 0.454, 0.416, 0.992, 0.434, 0.995, 0.814, 0.405, 0.998 0.634 0.405
lbfgs 0.998, 1.000, 1.000, 0.983, 1.000, 1.000, 0.999, 1.000 1.000 0.983

With adam, the outcome depends heavily on the seed: some runs are excellent (0.998) and others are worse than random (0.405), presumably because the training gets stuck before the network has learned the curve. With lbfgs, which suits small datasets, every seed works. The lesson is that an autoencoder's outlier score is only as good as its training, so always run several seeds and look at the spread before you trust a single run.

Next, the width of the bottleneck, with lbfgs and 8 seeds each:

Hidden layers Median AUC Minimum AUC
16-1-16 1.000 0.983
16-2-16 0.959 0.843
16-8-16 0.994 0.857

The narrowest bottleneck is both the best and the most reliable. With 2 or 8 units the network has room to reproduce points that are off the curve as well, so the worst seed drops from 0.983 to about 0.85. This is the central tension of autoencoders: the bottleneck must be narrow enough that outliers cannot squeeze through it.

Comparison with the earlier methods on dataset B

lofB = -LocalOutlierFactor(n_neighbors=20).fit(XBs).negative_outlier_factor_
isoB = -IsolationForest(random_state=0).fit(XBs).score_samples(XBs)
ocsB = -OneClassSVM(kernel="rbf", gamma="scale", nu=0.01).fit(XBs).decision_function(XBs)
Method ROC AUC Planted outliers in top 6
PCA reconstruction (k = 1) 0.469 0
Autoencoder (16-1-16) 0.998 4
LOF (k = 20) 0.994 4
Isolation Forest 0.964 0
One-Class SVM 0.863 1

Figure 4: ROC AUC on both datasets. On dataset A (left) the bars show the AUC separately for the two kinds of outlier. On dataset B (right) there is one bar per method.

The autoencoder (0.998) edges out LOF (0.994) here, but this is a small difference on 6 planted points, and LOF needed no training and no tuning beyond k. The honest reading is that on this dataset a good autoencoder and LOF are equally good, and the autoencoder is the more expensive and less predictable of the two. The real advantage of the autoencoder is scale and dimension: on wide data (hundreds of features, as in sensor or image data), neighbour searches deteriorate while an autoencoder still learns a compact description.

Novelty detection

As with the One-Class SVM, the natural use of a reconstruction model is to train on clean data and score new observations. I set a threshold at the 99th percentile of the training error and flag anything above it.

clean = StandardScaler().fit(arc)
ae_nov = autoencoder(clean.transform(arc), (16, 1, 16), seed=0)
newpts = np.array([[0.0, -1.0], [1.0, -0.1], [0.0, -0.2], [1.2, 1.2]])     # on curve, on curve, off curve, far off
err = recon_error(ae_nov, clean.transform(newpts), False)
thr = np.percentile(recon_error(ae_nov, clean.transform(arc), False), 99)
print("threshold = %.4f" % thr)
print("new-point errors:", np.round(err, 4), "| flagged:", err > thr)

The threshold is 0.0280. The two new points on the curve have errors of 0.0001 and 0.0004 and are not flagged. The two points off the curve have errors of 1.1668 and 0.1902 and are both flagged. Look at the order of the last two, though: the point at (1.2, 1.2), which is the farthest from the data, has a smaller error than the point at (0, −0.2). A reconstruction error is the distance from the point to the curve the network learned, and outside the training range the network's output is not reliable. So read the error as a ranking against the training errors, not as a distance.

Practical notes

  • Scale your features. Both PCA and the network are sensitive to the scale, so standardise first and fit the scaler on training data only.
  • Use \(T^2\) and \(Q\) together for PCA, since each one is blind to the other kind of outlier (Figure 1). If you must use one number, the full Mahalanobis distance covers both here.
  • Pick the bottleneck deliberately. Start from the scree plot or from the held-out reconstruction error, and prefer the narrowest bottleneck that rebuilds regular points well.
  • Run several seeds and average the errors, or at least report the spread. A single run of a neural autoencoder can be badly off, as the adam row above shows.
  • Contaminated training data is a risk. If a few outliers are in the training set, a wide enough network learns to rebuild them. Train on cleaned data if you can, or limit the capacity.
  • Linear structure needs no network. On dataset A the autoencoder (median 0.792) did not beat plain PCA (0.823), and it is slower and harder to explain.
  • Cost: PCA is a single SVD. The autoencoder here is tiny, but for real image or sensor data you would use a deep-learning library such as PyTorch or Keras with the same logic: train on normal data, score by reconstruction error.

Conclusion

In this post I discussed outlier scoring by reconstruction error. I verified PCA's reconstruction error against scikit-learn, showed that \(Q\) and \(T^2\) each detect a different kind of outlier, and showed that the best number of components is the true dimension of the signal. On a curved structure, PCA scored 0.469 while a 1-unit-bottleneck autoencoder scored 0.998, but the result depended on the optimiser and the seed, which is the price of the extra flexibility. In the next post I shall bring the whole series together with a benchmark of all the methods on several datasets and a decision guide for choosing between them.

References:

  1. G. E. Hinton and R. R. Salakhutdinov, "Reducing the Dimensionality of Data with Neural Networks", Science, 313(5786), 2006.
  2. J. E. Jackson and G. S. Mudholkar, "Control Procedures for Residuals Associated with Principal Component Analysis", Technometrics, 21(3), 1979. (A standard reference for the \(Q\) statistic.)
  3. scikit-learn documentation: sklearn.decomposition.PCA and sklearn.neural_network.MLPRegressor.

The code in this post was tested with Python 3 and scikit-learn 1.9.1.

One-Class SVM (Part 4)

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.5 and nu=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".
  • gamma is the parameter that matters: AUC ranges from 0.735 to 0.994 across the values I tried, and nu mostly 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:

  1. \(\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.
  2. \(\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.
  3. \(\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.
  4. \(\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 predict when \(\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 as Nystroem) 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:

  1. 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.
  2. scikit-learn documentation: sklearn.svm.OneClassSVM.

The code in this post was tested with Python 3 and scikit-learn 1.9.1.

Autoencoders and PCA reconstruction error (Part 5)

This is the fifth post in the series on model-based outlier detection. The earlier posts covered the basics and robust statistics , Isolatio...