This is the sixth and last post in the series on model-based outlier detection. Over the series I covered robust statistics, Isolation Forest, the Local Outlier Factor, the One-Class SVM, and Reconstruction error with PCA and Autoencoders. Each post used a dataset that was built to show off one method, which is fair for explaining an idea but not for choosing between methods. In this post I put all of them in the same race: 8 methods, 8 datasets, 20 repetitions each, with default settings and nothing tuned per dataset.
The summary first:
- k-NN distance and LOF came out on top, with a mean ROC AUC of 0.963 and 0.962 over the 8 datasets, and an average rank of 2.25 each among the 8 single methods. Each was within 0.01 of the best method on 6 of the 8 datasets.
- Isolation Forest was the most consistent. Its worst dataset was 0.926, the highest worst case of any method, although it was the clear winner on none of the datasets.
- Every specialist had a dataset where it collapsed. Mahalanobis scored 0.999 on the correlated data and 0.502 on the curved data. The One-Class SVM scored 0.995 on the correlated data and 0.747 on the curved one.
- PCA reconstruction error alone and an untuned autoencoder ranked last (mean AUC 0.703 and 0.771). The autoencoder fell to 0.388 on the small wine dataset.
- Averaging four methods did not beat the best single method on any dataset (mean AUC 0.917 against 0.963). It did beat the average single method on all 8, so it works as a hedge when you do not know the winner in advance.
- The main parameter can matter as much as the choice of method. LOF went from a mean AUC of 0.830 at k = 5 to 0.962 at k = 20.
The setup
The methods. Each method returns a score for every point, where higher means more outlying, and every dataset is standardised first.
| Method | What it scores | Settings |
|---|---|---|
| Robust z-score | largest |z| over the features, using the median and MAD | none |
| Mahalanobis | distance using a Ledoit-Wolf shrinkage covariance | none |
| k-NN distance | distance to the 20th nearest neighbour | k = 20 |
| LOF | local density ratio | k = 20 |
| Isolation Forest | path length in random trees | 200 trees |
| One-Class SVM | distance outside the learned boundary | RBF, gamma="scale", nu = 0.05 |
| PCA reconstruction | error after keeping 90% of the variance | 90% variance |
| Autoencoder | reconstruction error of a tanh network |
hidden layers (h, k, h), with k the number of PCA components for 90% variance, h = 16 if 10 features or fewer, else 32; lbfgs |
I also added a rank-average ensemble of Isolation Forest, LOF, Mahalanobis and PCA reconstruction (each score is converted to its rank, divided by the number of points, and the four are averaged). I fixed this combination before running anything and did not tune it on the results.
The datasets. Five are synthetic and three are real. The synthetic generators are new random draws of the datasets from the earlier posts, plus one new one with many irrelevant features. The real ones are classification datasets bundled with scikit-learn, recast as outlier detection: the majority class is "normal", and a small sample of another class is "anomalous".
| Dataset | Points | Planted outliers | Features | What it tests |
|---|---|---|---|---|
| Clusters (2-D) | 615 | 15 | 2 | three equal clusters, scattered global outliers |
| Varying density (2-D) | 407 | 7 | 2 | tight and loose cluster, local and global outliers (Part 3) |
| Correlated (10-D) | 1010 | 10 | 10 | 3 hidden factors; off-subspace and extreme outliers (Part 5) |
| Curved (2-D) | 606 | 6 | 2 | noisy parabola, outliers 0.6 to 0.7 off the curve (Part 5) |
| Noisy features (50-D) | 515 | 15 | 50 | 5 informative features and 45 pure noise; outliers shifted in the informative ones only |
| Breast cancer (30-D) | 378 | 21 | 30 | 357 benign cases; 21 malignant cases sampled per repetition |
| Wine (13-D) | 140 | 10 | 13 | wine classes 0 and 1 are normal; 10 of class 2 sampled per repetition |
| Digits 0 vs 6 (64-D) | 188 | 10 | 64 | 178 images of the digit 0; 10 images of the digit 6 sampled per repetition |
In each of the 20 repetitions, the synthetic data is generated again with a new seed, and the real datasets use a new random sample of anomalies. All methods run on the whole dataset with the outliers included, which is the same unsupervised setting as in the earlier posts. The scoring metric is the ROC AUC, with average precision as a second view.
import numpy as np
from sklearn.covariance import LedoitWolf
from sklearn.decomposition import PCA
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor, NearestNeighbors
from sklearn.neural_network import MLPRegressor
from sklearn.svm import OneClassSVM
def m_robust_z(X, seed):
med = np.median(X, axis=0); mad = 1.4826 * np.median(np.abs(X - med), axis=0)
sd = X.std(axis=0); mad = np.where(mad > 0, mad, np.where(sd > 0, sd, 1.0)) # guard constant columns
return np.abs((X - med) / mad).max(axis=1)
def m_mahal(X, seed):
return LedoitWolf().fit(X).mahalanobis(X)
def m_knn(X, seed):
return NearestNeighbors(n_neighbors=21).fit(X).kneighbors(X)[0][:, 20] # column 0 is the point itself
def m_lof(X, seed):
return -LocalOutlierFactor(n_neighbors=20).fit(X).negative_outlier_factor_
def m_iforest(X, seed):
return -IsolationForest(n_estimators=200, random_state=seed).fit(X).score_samples(X)
def m_ocsvm(X, seed):
return -OneClassSVM(kernel="rbf", gamma="scale", nu=0.05).fit(X).decision_function(X)
def m_pca(X, seed):
p = PCA(n_components=0.9, svd_solver="full").fit(X)
return ((X - p.inverse_transform(p.transform(X))) ** 2).sum(axis=1)
def m_ae(X, seed):
k90 = PCA(n_components=0.9, svd_solver="full").fit(X).n_components_
h = 16 if X.shape[1] <= 10 else 32
ae = MLPRegressor(hidden_layer_sizes=(h, k90, h), activation="tanh", solver="lbfgs",
max_iter=500, random_state=seed).fit(X, X)
return ((X - ae.predict(X)) ** 2).sum(axis=1)
The one new synthetic generator, and the function that recasts a classification dataset as outlier detection, look like this:
from sklearn.datasets import load_digits
def gen_noisy(seed): # 5 informative + 45 pure-noise features
r = np.random.RandomState(seed)
n, ni, nn = 500, 5, 45
Xr = r.normal(size=(n, ni + nn))
out = r.normal(size=(15, ni + nn)); out[:, :ni] += r.choice([-1, 1], size=(15, ni)) * 3.0
return np.vstack([Xr, out]), np.r_[np.zeros(n), np.ones(15)]
def digits_dataset(): # zeros are normal, sixes are the anomalies
D = load_digits(); Xn = D.data[D.target == 0]; Xa = D.data[D.target == 6]
def gen(seed):
r = np.random.RandomState(seed)
pick = r.choice(len(Xa), 10, replace=False)
return np.vstack([Xn, Xa[pick]]), np.r_[np.zeros(len(Xn)), np.ones(10)]
return gen
The loop that produces every number below runs each method on each repetition, scores it, and averages:
from scipy.stats import rankdata
from sklearn.metrics import roc_auc_score, average_precision_score
from sklearn.preprocessing import StandardScaler
def rank01(s):
return rankdata(s) / len(s)
ENSEMBLE_PARTS = ["Isolation Forest", "LOF", "Mahalanobis", "PCA reconstruction"]
for dn, gen in DATASETS.items():
for rep in range(20):
X, y = gen(rep)
Xs = StandardScaler().fit_transform(X)
sc = {mn: f(Xs, rep) for mn, f in METHODS.items()}
sc["Rank-average ensemble"] = np.mean([rank01(sc[p]) for p in ENSEMBLE_PARTS], axis=0)
for mn, s in sc.items():
auc[dn][mn].append(roc_auc_score(y, s)); ap[dn][mn].append(average_precision_score(y, s))
Results: ROC AUC on every dataset
Each cell is the mean over 20 repetitions. The standard deviation across repetitions is at most 0.1 for most cells. The largest ones are on the curved data for the One-Class SVM (0.162) and for the robust z-score and Mahalanobis (0.146 each); the full table with standard deviations is in benchmark_run_output.txt.
| Method | Clusters | Varying density | Correlated | Curved | Noisy features | Breast cancer | Wine | Digits |
|---|---|---|---|---|---|---|---|---|
| Robust z-score | 0.746 | 0.849 | 0.916 | 0.527 | 0.978 | 0.920 | 0.878 | 0.893 |
| Mahalanobis | 0.816 | 0.867 | 0.999 | 0.502 | 0.981 | 0.889 | 0.863 | 0.974 |
| k-NN distance | 0.947 | 0.914 | 0.988 | 0.995 | 0.983 | 0.934 | 0.955 | 0.986 |
| LOF | 0.945 | 1.000 | 0.999 | 0.999 | 0.983 | 0.916 | 0.874 | 0.984 |
| Isolation Forest | 0.942 | 0.980 | 0.926 | 0.947 | 0.935 | 0.938 | 0.944 | 0.989 |
| One-Class SVM | 0.942 | 0.992 | 0.995 | 0.747 | 0.926 | 0.869 | 0.791 | 0.869 |
| PCA reconstruction | 0.648 | 0.860 | 0.804 | 0.458 | 0.638 | 0.788 | 0.638 | 0.789 |
| Autoencoder | 0.882 | 0.875 | 0.884 | 0.953 | 0.758 | 0.770 | 0.388 | 0.660 |
| Rank-average ensemble | 0.892 | 0.958 | 0.972 | 0.821 | 0.941 | 0.899 | 0.881 | 0.972 |
Bold marks results within 0.01 of the best method on that dataset (the ensemble was never within 0.01).
Figure 1: the same table as a heatmap. The vertical line separates the synthetic datasets (left) from the real ones (right).
Summaries over the 8 datasets:
| Method | Mean AUC | Worst-dataset AUC | Mean average precision | Average rank (of 9) | Datasets within 0.01 of best |
|---|---|---|---|---|---|
| k-NN distance | 0.963 | 0.914 | 0.665 | 2.38 | 6 |
| LOF | 0.962 | 0.874 | 0.721 | 2.38 | 6 |
| Isolation Forest | 0.950 | 0.926 | 0.538 | 3.25 | 3 |
| Rank-average ensemble | 0.917 | 0.821 | 0.428 | 4.62 | 0 |
| One-Class SVM | 0.891 | 0.747 | 0.475 | 5.38 | 3 |
| Mahalanobis | 0.862 | 0.502 | 0.501 | 5.25 | 2 |
| Robust z-score | 0.838 | 0.527 | 0.369 | 6.00 | 1 |
| Autoencoder | 0.771 | 0.388 | 0.335 | 7.25 | 0 |
| PCA reconstruction | 0.703 | 0.458 | 0.245 | 8.50 | 0 |
What the numbers say
1. The simple neighbour methods are hard to beat. k-NN distance and LOF are essentially tied on the average, and both are cheap and need only one parameter. They differ where the density varies: on the varying-density data LOF scores 1.000 and plain k-NN distance 0.914, which is exactly the situation LOF was designed for (Part 3). The gap is larger in the average precision (0.970 against 0.477 on the same dataset), and LOF has the best mean average precision overall (0.721 against 0.665). On the real datasets, k-NN distance did better than LOF on breast cancer (0.934 against 0.916) and wine (0.955 against 0.874).
2. Isolation Forest is the safe choice rather than the best choice. It never fell below 0.926, and its range across the 8 datasets is 0.926 to 0.989. But it was the clear winner on none of them, and its average precision (0.538) is well below LOF's, which means its top-ranked points are less often true outliers.
3. The specialists behave as the earlier posts predicted. Mahalanobis exploits correlations, so it is excellent on the correlated data (0.999, Part 5) and useless on the curved data (0.502), where a single covariance ellipse cannot describe the structure. The One-Class SVM does well on the first three datasets (0.942, 0.992 and 0.995) but drops to 0.747 on the curve and 0.791 on the wine data, where one global kernel width does not suit the structure (Part 4). PCA reconstruction error finds only the points that break the correlations (Part 5), so it ranks last on average when most of the outliers are simply far away.
4. The autoencoder is the least reliable here. Its mean AUC was 0.771, with a worst case of 0.388 on the wine data. This is an untuned autoencoder with a rule-of-thumb bottleneck on datasets of only 140 to 1010 points, so the result says little about what a carefully tuned deep model could do on large image or sensor data. What it does show is that the autoencoder's flexibility (Part 5, where it reached 0.998 on the curve) comes with the need for tuning and several seeds. On the curved data it did reach a mean AUC of 0.953, which is far ahead of Mahalanobis, the One-Class SVM and PCA, although still behind k-NN distance and LOF.
5. Averaging methods is a hedge, not a boost. The ensemble scored below the best single method on every dataset (by 0.017 to 0.178), and its mean AUC (0.917) is well below k-NN distance (0.963). It did beat the average single method on every dataset (by 0.021 to 0.090). This is the real benefit: if you do not know in advance which method suits your data, an ensemble avoids the worst picks. But I built it from two weak methods (Mahalanobis and PCA reconstruction) for the sake of diversity, and a different combination would give different numbers. I did not try other combinations, because choosing the best one after seeing these results would bias the comparison.
6. The ranking depends on the metric. The average precision is far below the AUC for every method, since with 1% to 5% outliers the top of the ranking matters most. Isolation Forest, for example, has a mean AUC of 0.950 but a mean average precision of only 0.538. If you will inspect only the top few alerts, check the precision at the top of the list and not only the AUC.
Figure 2: left, the average rank of the 8 single methods (lower is better). Right, mean AUC against the median run time per dataset on a log scale.
On cost, the run times here are for datasets of at most 1010 points. Isolation Forest (about 0.2 seconds) and the autoencoder (about 0.26 seconds) are two orders of magnitude slower than the others (about 0.001 to 0.002 seconds), but at this size the difference is not important, and I did not measure how any of the methods scales to larger data. That is a separate experiment.
How sensitive is each method to its main parameter?
The benchmark used one fixed setting per method. To see how much that choice matters, I varied the main parameter of three methods over 8 repetitions per dataset.
def lof_fn(X, k): return -LocalOutlierFactor(n_neighbors=min(k, len(X) - 1)).fit(X).negative_outlier_factor_
def ocs_fn(X, nu): return -OneClassSVM(kernel="rbf", gamma="scale", nu=nu).fit(X).decision_function(X)
def pca_fn(X, v):
p = PCA(n_components=v, svd_solver="full").fit(X)
return ((X - p.inverse_transform(p.transform(X))) ** 2).sum(axis=1)
# for each dataset and repetition: standardise, score with each setting, average the ROC AUC
| Method and setting | Mean AUC over datasets | Worst dataset |
|---|---|---|
| LOF, k = 5 | 0.830 | 0.474 |
| LOF, k = 10 | 0.922 | 0.671 |
| LOF, k = 20 | 0.962 | 0.859 |
| LOF, k = 50 | 0.967 | 0.934 |
| One-Class SVM, nu = 0.01 | 0.873 | 0.780 |
| One-Class SVM, nu = 0.05 | 0.891 | 0.724 |
| One-Class SVM, nu = 0.1 | 0.895 | 0.683 |
| One-Class SVM, nu = 0.2 | 0.897 | 0.639 |
| PCA, 70% variance kept | 0.731 | 0.460 |
| PCA, 80% variance kept | 0.719 | 0.460 |
| PCA, 90% variance kept | 0.711 | 0.460 |
| PCA, 95% variance kept | 0.675 | 0.460 |
| PCA, 99% variance kept | 0.665 | 0.460 |
Figure 3: mean ROC AUC (blue) and the individual datasets (grey) against the main parameter of each method.
- LOF needs a large enough k. The mean AUC rises from 0.830 at k = 5 to 0.962 at k = 20, and the worst dataset from 0.474 to 0.859. The average change per dataset between the best and the worst k is 0.155, and the largest is 0.469 on the wine data. This is why the benchmark used k = 20. A very small k should be avoided on small datasets, and the wine data has only 140 points, so even k = 20 is a large share of it.
- The One-Class SVM's nu moves the mean little but the worst case a lot. The mean AUC only changes between 0.873 and 0.897, but the worst dataset falls from 0.780 (nu = 0.01) to 0.639 (nu = 0.2). The average per-dataset change is 0.075, and the largest is 0.177 on the clusters data.
- PCA gets slightly worse as you keep more variance (0.731 at 70% down to 0.665 at 99%), which is consistent with the model absorbing the outliers when it has more components (Part 5). The per-dataset change is large on some datasets (average 0.138, largest 0.331 on the digits data).
A practical decision guide
Figure 4: a starting point built from this benchmark, with the evidence for each row. It is not a rule.
In words:
- Start with k-NN distance or LOF (k = 20) after standardising. They had the best average rank and cost milliseconds here. Prefer LOF when the density of the data varies, or when you care about the top of the ranking.
- Use Isolation Forest when you want the most consistent result, or when the data is large, since it works on subsamples of the data.
- Add Mahalanobis, or PCA with \(T^2\) and \(Q\) together, when your features are strongly correlated and breaking the relationships is what counts (sensors, risk factors, financial series). Do not use it alone when the structure may be curved.
- Use the One-Class SVM or an autoencoder when you have a clean reference set and need to score new observations. Tune gamma and nu for the SVM, and train the autoencoder with several seeds.
- Try an autoencoder with a narrow bottleneck for curved structures in many features, such as images, signals and embeddings, and compare it with LOF before you trust it.
- Whatever you choose, treat the score as a ranking, set the cutoff from the cost of a false alarm, and run at least two different methods. Look at the points where they disagree, since those are the most informative ones.
Limitations
- The synthetic datasets are mine, and each was built to contain a particular kind of outlier. They are new random draws, but their structure is fixed, so a different set of synthetic problems could change the ranking.
- The real datasets are classification datasets recast as outlier detection. The "anomalies" are samples of another class, which is a standard device but is not the same as genuinely rare events in practice. Each has at most a few hundred points.
- All methods used default or rule-of-thumb settings and were not tuned per dataset. A tuned One-Class SVM or autoencoder would likely do better than shown here.
- The scores were computed on the same data that the models were fitted on, with the outliers present. A clean-train, score-new setup would favour the One-Class SVM and the autoencoder.
- With 8 datasets, small differences in the average rank, such as 2.25 against 3.00, are not strong evidence. The big gaps (neighbour methods against PCA reconstruction, for instance) are more reliable.
- Run times were measured on small data and say nothing about scaling.
Conclusion
In this post I compared eight outlier detectors, and a rank-average ensemble, on eight datasets with the same protocol. The simplest methods, k-NN distance and LOF, were the best on average (mean AUC 0.963 and 0.962). Isolation Forest was the most consistent, the specialists were excellent on their own kind of data and poor on others, and the main parameter of a method (the k of LOF, for example) could matter as much as the choice of method. If I had to condense six posts into one sentence, it would be this: standardise, start with a neighbour-based score, check it against a second method of a different kind, and spend your effort on choosing the cutoff from the cost of a false alarm. This completes the series. Applying the same protocol to financial time series, where the structure changes over time, would be a possible next step.
References:
- M. M. Breunig, H.-P. Kriegel, R. T. Ng and J. Sander, "LOF: Identifying Density-Based Local Outliers", Proceedings of the ACM SIGMOD International Conference on Management of Data, 2000.
- F. T. Liu, K. M. Ting and Z.-H. Zhou, "Isolation Forest", Proceedings of the IEEE International Conference on Data Mining, 2008.
- B. Schölkopf et al., "Estimating the Support of a High-Dimensional Distribution", Neural Computation, 13(7), 2001.
- O. Ledoit and M. Wolf, "A Well-Conditioned Estimator for Large-Dimensional Covariance Matrices", Journal of Multivariate Analysis, 88(2), 2004.
- scikit-learn documentation: the
sklearn.neighbors,sklearn.ensemble,sklearn.svm,sklearn.decomposition,sklearn.covarianceandsklearn.neural_networkmodules, and the bundled datasetsload_breast_cancer,load_wineandload_digits.
The code in this post was tested with Python 3 and scikit-learn 1.9.1.



