Module contents
Lesson 19 of 24Core 110 min

Unsupervised anomaly detection

Unify anomaly detectors as density, distance, isolation and reconstruction scores; compare robust Mahalanobis, LOF, Isolation Forest, One-Class SVM and PCA, with evaluation at low prevalence.

After this lesson you can

  • Classify point, contextual and collective anomalies and formulate scores and thresholds.
  • Implement Isolation Forest and LOF and explain each detector's geometry.
  • Use robust Mahalanobis distance and explain masking and swamping.
  • Apply One-Class SVM and PCA reconstruction and select detectors by data structure.
  • Evaluate with PR-AUC and precision at k and reason about base rates.

Before you start

Motivation: rare events do not come labeled

A firewall records millions of connections a day and a few are attacks; a bank processes payments and a few are fraud; a turbine emits vibrations and occasionally one signals a fault; a data pipeline receives a column from a sensor stuck at zero for hours. In every case you seek the same thing: observations unlike the others. And in every case the same problem occurs: you do not have a large labeled set of rare examples, because they are infrequent, change over time, and sometimes have never been seen. You cannot train a classifier. What you have is unlabeled data, almost all normal, and a model of what “normal” means.

That is the task of unsupervised anomaly detection, one of the most valuable uses of unsupervised learning and one of the hardest to evaluate. This lesson organizes it around one idea: every detector is a score s(x)s(\vb{x}) saying how much x\vb{x} deviates from normal, plus a threshold deciding when to alert. Detectors differ in what deviation means: low density, distance from neighbors, ease of isolation, falling outside the region covering most data, or inability to be reconstructed by a low-rank model.

Score choice matters more than it seems. The next cell builds a cloud with correlation 0.9 and 10 anomalies placed at the distance from the center where many normal observations live, but in the direction where data barely vary. Euclidean distance to the mean is the most naive score; Mahalanobis accounts for covariance; and −log⁡p^-\log \hat{p} with kernel density accounts for local shape. All are evaluated using the same labels (used only for measurement, never fitting).

[ ]One cloud, three scoresBrowser
import numpy as np
from sklearn.neighbors import KernelDensity
from sklearn.metrics import average_precision_score, roc_auc_score

rng = np.random.default_rng(0)
Sigma = np.array([[1.0, 0.9], [0.9, 1.0]])
normales = rng.multivariate_normal([0, 0], Sigma, size=490)
# 10 anomalías cerca del centro, sobre la dirección en la que los datos casi no varían (1, -1)/sqrt(2)
t = rng.normal(0, 0.15, 10)
anomalias = np.outer(np.full(10, 1.8) * rng.choice([-1, 1], 10) + t, [1, -1]) / np.sqrt(2)
X = np.vstack([normales, anomalias])
y = np.r_[np.zeros(490), np.ones(10)].astype(bool)

mu = X.mean(0)
S_inv = np.linalg.inv(np.cov(X.T))
puntuaciones = {
    "distancia euclídea a la media": np.linalg.norm(X - mu, axis=1),
    "Mahalanobis": np.einsum("ij,jk,ik->i", X - mu, S_inv, X - mu),
    "-log densidad (KDE, h=0.3)": -KernelDensity(bandwidth=0.3).fit(X).score_samples(X),
}
for nombre, s in puntuaciones.items():
    print(f"{nombre:32s} ROC-AUC = {roc_auc_score(y, s):.3f}   PR-AUC = {average_precision_score(y, s):.3f}")
print("distancia euclídea típica de una anomalía:", round(float(np.linalg.norm(anomalias - mu, axis=1).mean()), 2),
      "| de un normal:", round(float(np.linalg.norm(normales - mu, axis=1).mean()), 2))

With Euclidean distance, anomalies are on average 1.78 from the center and normal points 1.15 (normal points extend along the diagonal and anomalies do not): the score barely separates them (ROC-AUC 0.812 and PR-AUC 0.053, little above the 0.02 chance level at 2% prevalence). In the minor direction standard deviation is 0.1≈0.32\sqrt{0.1} \approx 0.32, so these anomalies are over five standard deviations away: Mahalanobis distance, measuring in that metric, ranks almost all near the top (PR-AUC 0.991). Kernel density is in between (ROC-AUC 0.975 but PR-AUC 0.295): it sees that those regions have low density, but also flags many normal tail points. Notice that two scores with similarly high ROC-AUC (0.975 versus 1.000) have very different PR-AUC. We return to this in evaluation.

Anomalies, scores and thresholds

Begin by fixing the vocabulary.

Separating score and threshold is more than convenience. The score is what the model learns and what PR-AUC or ROC-AUC measure, neither depending on τ\tau. The threshold is an operational decision: how many alerts the team can handle, and the cost of a false alarm versus a missed anomaly. scikit-learn’s contamination parameter does not estimate contamination: it sets τ\tau to the training-score quantile leaving that fraction above it. Choosing τ\tau this way is legitimate, but says “alert on the rarest 5%,” not “I know 5% are anomalies.”

Types of anomalies (Chandola, Banerjee and Kumar, 2009):

  • Point anomalies: one observation differs from the rest. This is the case covered by nearly all detectors in this lesson. A €90,000 payment on an account moving €200 a month.
  • Contextual anomalies: the observation is generally normal but anomalous in context. A temperature of 30 °C is not unusual; in January it is. Detecting these requires separating contextual attributes (date, user, sensor) from behavioral attributes and modeling the latter conditional on the former; this is the domain of time series (change-point detection).
  • Collective anomalies: no single observation is unusual, but the group is. One hundred connections to consecutive ports, each harmless. A microcluster of 6 close points far from the rest is a geometric example, challenging every detector measuring density with neighborhoods smaller than the group.

Supervision regimes. If training contains only normal data, this is novelty detection (or semi-supervised detection). If contaminated, it is outlier detection (purely unsupervised), and the task is harder because the model may learn anomalies as normal. Weak supervision occupies the middle: a few confirmed anomalies, heuristic rules, or review of initial alerts help calibrate the threshold, estimate contamination, or evaluate; ADBench (Han and coauthors, 2022) compares 30 algorithms on 57 datasets precisely to study the role of supervision and anomaly type.

Why is density the natural score?

An optimality argument justifies measuring “rarity” using normal-data density.

Proof

By the Neyman–Pearson lemma, the most powerful level-α\alpha test rejects when likelihood ratio q(x)/p(x)q(\vb{x})/p(\vb{x}) exceeds a constant kk, accepts when it is lower, and randomizes on equality if needed. On AA, q/p=1/(V p(x))q/p = 1/(V\,p(\vb{x})) (equal to +∞+\infty where p=0p = 0), a strictly decreasing function of p(x)p(\vb{x}); outside AA, q=p=0q = p = 0 and that set has probability zero under both hypotheses. Thus q/p>kq/p > k is equivalent to p(x)<1/(kV)=:cp(\vb{x}) < 1/(kV) =: c, and q/p=kq/p = k to p(x)=cp(\vb{x}) = c. ■\blacksquare

∎

In other words: if you do not know what anomalies look like and assume only that they can be anywhere, normal-density level sets are optimal acceptance regions, and −log⁡p(x)-\log p(\vb{x}) is the best score. This principle underlies density estimation and, as you will see, One-Class SVM, which estimates a level set without estimating density. Everything else approximates pp when pp cannot be estimated well, especially in high dimensions and with contamination. Ruff and coauthors’ 2021 review connects classical and deep detectors through three families (generative models, one-class classification and reconstruction); this lesson adds local distances and isolation, which do not estimate pp but rank points similarly.

Density scores: Gaussian, mixture and kernels

If you estimate p^\hat{p}, the score is s(x)=−log⁡p^(x)s(\vb{x}) = -\log\hat{p}(\vb{x}). Three familiar families:

  • A Gaussian N(μ^,Σ^)\Normal(\hat{\vb{\mu}}, \hat{\mat{\Sigma}}): the score is, up to constants, Mahalanobis distance, discussed next.
  • A Gaussian mixture p^(x)=∑j=1KπjN(x;μj,Σj)\hat{p}(\vb{x}) = \sum_{j=1}^K \pi_j\Normal(\vb{x}; \vb{\mu}_j, \mat{\Sigma}_j) fitted by EM: models several groups at the cost of choosing KK.
  • A kernel density estimate p^h(x)=1n∑iKh(x−xi)\hat{p}_h(\vb{x}) = \frac1n\sum_i K_h(\vb{x} - \vb{x}_i): nonparametric, with bandwidth hh as its only tuning parameter.

They share two problems. First is self-contamination: when scoring training data themselves, each point contributes to its density. With Gaussian KDE in the plane, p^h(xi)≥Kh(0)/n=1/(2πnh2)\hat{p}_h(\vb{x}_i) \ge K_h(\vb{0})/n = 1/(2\pi n h^2), so no training point can score above log⁡(2πnh2)\log(2\pi n h^2): a small bandwidth protects isolated outliers because each explains itself. The solution is scoring with leave-one-out density or evaluating on unseen data. Second, a mixture with too many components can dedicate one to anomalies themselves: the detector zoo shows a K=4K = 4 component capturing the microcluster and treating it as normal.

A third problem is dimension: small-radius neighborhoods empty out and p^\hat{p} ceases to distinguish regions, so full-density scores lose resolution much earlier than scores using other information (neighbor distances, isolation, reconstruction).

Classical and robust Mahalanobis

Mahalanobis distance measures how many standard deviations x\vb{x} is from the center in the covariance metric: d2(x)=(x−μ)⊤Σ−1(x−μ)d^2(\vb{x}) = (\vb{x} - \vb{\mu})\T\mat{\Sigma}\inv(\vb{x} - \vb{\mu}). Its great virtue is exact calibration under normality.

Proof

Since Σ=UΛU⊤\mat{\Sigma} = \mat{U}\mat{\Lambda}\mat{U}\T with diagonal Λ\mat{\Lambda} of positive entries, symmetric root Σ−1/2=UΛ−1/2U⊤\mat{\Sigma}^{-1/2} = \mat{U}\mat{\Lambda}^{-1/2}\mat{U}\T exists. Let Z=Σ−1/2(X−μ)\vb{Z} = \mat{\Sigma}^{-1/2}(X - \vb{\mu}): it is a linear transform of a Gaussian vector, hence Gaussian, with mean 0\vb{0} and covariance Σ−1/2ΣΣ−1/2=Ip\mat{\Sigma}^{-1/2}\mat{\Sigma}\mat{\Sigma}^{-1/2} = \mat{I}_p. Components are therefore independent N(0,1)\Normal(0,1) and d2=Z⊤Z=∑i=1pZi2∼χp2d^2 = \vb{Z}\T\vb{Z} = \sum_{i=1}^p Z_i^2 \sim \chi^2_p by definition. The probability that d2>τd^2 > \tau is 1−Fχp2(τ)1 - F_{\chi^2_p}(\tau), equal to α\alpha exactly when τ=χp,1−α2\tau = \chi^2_{p,1-\alpha}. ■\blacksquare

∎

This connects to the gamma family: a χp2\chi^2_p is a Gamma(p/2,2)\mathrm{Gamma}(p/2, 2) (exponential and gamma family). But the theorem assumes known parameters. In practice you estimate μ^\hat{\vb{\mu}} and Σ^\hat{\mat{\Sigma}} from the same data, and the result is only approximate, worsening as nn becomes small relative to pp:

[ ]Chi-squared calibration with known and estimated parametersBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(1)
p = 5
A = rng.normal(size=(p, p))
Sigma = A @ A.T + 0.5 * np.eye(p)
mu = rng.normal(size=p)
corte = stats.chi2.ppf(0.99, df=p)

def d2(X, m, S):
    D = X - m
    return np.einsum("ij,jk,ik->i", D, np.linalg.inv(S), D)

# parámetros verdaderos: d² ~ chi²_p y la tasa de falsos positivos es exactamente alfa
X = rng.multivariate_normal(mu, Sigma, size=200_000)
d = d2(X, mu, Sigma)
print(f"parámetros conocidos: media d² = {d.mean():.3f} (p = {p}), fracción > chi2_(5, 0.99) = {(d > corte).mean():.4f}")

# parámetros estimados con n puntos y evaluados en datos nuevos
for n in (30, 100, 1000):
    tasas = []
    for _ in range(300):
        Xn = rng.multivariate_normal(mu, Sigma, size=n)
        Xt = rng.multivariate_normal(mu, Sigma, size=2000)
        tasas.append((d2(Xt, Xn.mean(0), np.cov(Xn.T)) > corte).mean())
    print(f"n = {n:4d}: tasa de falsos positivos media = {np.mean(tasas):.4f}")

With known parameters, E[d2]=p=5\E[d^2] = p = 5 (the cell gives 4.985) and false-positive rate is 0.0100, the nominal rate. With parameters estimated from n=30n = 30 points, the actual rate is 0.0531, five times nominal; with n=100n = 100, 0.0187; with n=1000n = 1000, 0.0107. The χ2\chi^2 threshold is optimistic with few data: do not use it as a guarantee without checking n/pn/p.

Masking and swamping

The more serious problem is different: classical mean and covariance are not robust. A single sufficiently distant point can drag the mean and expand covariance arbitrarily. When outliers are numerous and clustered, the effect is twofold:

  • Masking: outliers make estimated covariance so large that the ellipse includes them. They go undetected because there are other outliers.
  • Swamping: the same distortion (shifted mean, tilted ellipse) excludes normal points, which are flagged as outliers.

Check it. The figure has 100 normal points with correlation 0.6 and a group of mm outliers. Left, the 97.5% Mahalanobis ellipses using classical mean and covariance (blue) and MCD (dashed orange), defined next; right, the distance–distance plot proposed by Rousseeuw and Van Driessen (1999): each point’s robust versus classical distance.

InteractiveMasking
Data and 97.5% ellipses
Diagnostic plot: robust d2\sqrt{d^2} versus classical
002244668810101212enmascarados distancia clásicadistancia robusta
  • normal points
  • outliers
  • classical mean and ellipse
  • MCD mean and ellipse
25
6.0
-45°
0.75
Contamination m/nm/n20 %
Outliers detected: classical0 / 25
Outliers detected: MCD25 / 25
Flagged normal points: classical · MCD2 · 0 of 100
Masking: outliers drag the mean and widen classical covariance until the ellipse includes them (0/25 detected). MCD excludes them (25/25).
100 normal points (gray) with covariance [[1,0.6],[0.6,1]][[1, 0.6], [0.6, 1]] and a group of mm outliers (red, standard deviation 0.35) at distance δ\delta from the origin in direction φ\varphi. Initially m=25m = 25 outliers are distance 6 in direction −45°-45°, perpendicular to normal points' greatest spread: the classical 97.5% ellipse includes them all (0 of 25 detected) because covariance has grown toward them, whereas the MCD ellipse, with support h/n=0.75h/n = 0.75, excludes them (25 of 25). In the diagnostic plot outliers lie in the shaded region: classical distance below threshold and robust distance far above. Increase mm: with 35 or 40 outliers contamination already exceeds 1−h/n=25 %1 - h/n = 25\,\% and MCD still holds (the guarantee applies below that; above it, it may or may not fail), but with m=45m = 45 (31%) the minimum-determinant subset follows outliers: the MCD ellipse includes them and excludes 8 normal points, which is swamping. Set h/n=0.5h/n = 0.5 and it succeeds again, even with m=70m = 70. With m=0m = 0, the ellipses almost coincide.

The MCD estimator

Rousseeuw’s (1984, 1985) idea is not to use all data to estimate cloud shape.

A covariance determinant is, up to constants, the square of its ellipsoid’s volume: MCD seeks the most compact subset of size hh. With at most n−hn - h outliers there is a subset of hh points excluding them all, so tolerated contamination is of order 1−h/n1 - h/n: for data in general position, its breakdown point (smallest fraction of points that can move the estimate arbitrarily when moved at will) is min⁡(n−h+1, h−p)/n\min(n - h + 1,\, h - p)/n, maximal and near 50% with h≈(n+p+1)/2h \approx (n + p + 1)/2 (Rousseeuw and Van Driessen, 1999). The price of robustness: small hh uses fewer data and loses estimator efficiency, while the exact solution is combinatorial ((nh)\binom{n}{h} subsets).

Rousseeuw and Van Driessen’s FastMCD relies on an elegant result: a step improving any subset.

Proof

Sum the quadratic form over H1H_1 using that a scalar equals its trace and trace is cyclic: ∑i∈H1d1(i)2=tr⁡(S1−1∑i∈H1(xi−t1)(xi−t1)⊤)=h tr⁡(S1−1S1)=hp\sum_{i\in H_1} d_1(i)^2 = \tr\big(\mat{S}_1\inv \sum_{i\in H_1}(\vb{x}_i - \vb{t}_1)(\vb{x}_i - \vb{t}_1)\T\big) = h\,\tr(\mat{S}_1\inv\mat{S}_1) = hp. Since H2H_2 collects the hh smallest d12d_1^2 values, ∑i∈H2d1(i)2≤∑i∈H1d1(i)2=hp\sum_{i\in H_2} d_1(i)^2 \le \sum_{i\in H_1} d_1(i)^2 = hp.

Let S3=1h∑i∈H2(xi−t1)(xi−t1)⊤\mat{S}_3 = \frac1h\sum_{i\in H_2}(\vb{x}_i - \vb{t}_1)(\vb{x}_i - \vb{t}_1)\T, the scatter of H2H_2 around t1\vb{t}_1. It decomposes as S3=S2+(t2−t1)(t2−t1)⊤⪰S2\mat{S}_3 = \mat{S}_2 + (\vb{t}_2 - \vb{t}_1)(\vb{t}_2 - \vb{t}_1)\T \succeq \mat{S}_2, and tr⁡(S1−1S3)=1h∑H2d12≤p\tr(\mat{S}_1\inv\mat{S}_3) = \frac1h\sum_{H_2} d_1^2 \le p. Eigenvalues μ1,…,μp≥0\mu_1, \dots, \mu_p \ge 0 of S1−1/2S3S1−1/2\mat{S}_1^{-1/2}\mat{S}_3\mat{S}_1^{-1/2} sum to at most pp, and by the arithmetic–geometric mean inequality,

det⁡S3det⁡S1=∏jμj≤(∑jμjp)p≤1.\frac{\det\mat{S}_3}{\det\mat{S}_1} = \prod_j \mu_j \le \Big(\frac{\sum_j\mu_j}{p}\Big)^p \le 1 .

Since S3⪰S2⪰0\mat{S}_3 \succeq \mat{S}_2 \succeq 0, det⁡S2≤det⁡S3≤det⁡S1\det\mat{S}_2 \le \det\mat{S}_3 \le \det\mat{S}_1. ■\blacksquare

∎

Repeating C-steps from any start yields a nonincreasing determinant sequence that stops at a local minimum. FastMCD launches many random starts (with p+1p + 1 points), applies only two C-steps, discards the worst and takes the best to convergence. Finally it refits using points whose robust distance does not exceed χp,0.9752\chi^2_{p,0.975}. Implement it from scratch in the next cell and check against scikit-learn:

[ ]MCD from scratch: C-steps, starts and consistencyBrowser
import numpy as np
from scipy import stats
from sklearn.covariance import MinCovDet

def distancias2(X, mu, S):
    D = X - mu
    return np.einsum("ij,jk,ik->i", D, np.linalg.inv(S), D)

def paso_c(X, mu, S, h):
    """Un paso C: los h puntos de menor distancia de Mahalanobis y su media y covarianza."""
    idx = np.argsort(distancias2(X, mu, S))[:h]
    return X[idx].mean(0), np.cov(X[idx].T, bias=True), np.sort(idx)

def mcd(X, h_frac=0.75, n_inicios=100, n_mejores=10, seed=0):
    """FastMCD simplificado: muchos inicios, dos pasos C cada uno y convergencia solo para los mejores."""
    rng = np.random.default_rng(seed)
    n, p = X.shape
    h = int(h_frac * n)
    candidatos = []
    for s in range(n_inicios):
        idx = rng.choice(n, p + 1, replace=False)
        mu, S = X[idx].mean(0), np.cov(X[idx].T, bias=True)
        while np.linalg.det(S) < 1e-12:                    # soporte degenerado: añade un punto
            idx = np.append(idx, rng.integers(n))
            mu, S = X[idx].mean(0), np.cov(X[idx].T, bias=True)
        for _ in range(2):
            mu, S, sop = paso_c(X, mu, S, h)
        candidatos.append((np.linalg.det(S), mu, S))
    candidatos.sort(key=lambda t: t[0])
    mejor = (np.inf, None, None)
    for det, mu, S in candidatos[:n_mejores]:
        previo, dets = None, [det]
        for _ in range(50):
            mu, S, sop = paso_c(X, mu, S, h)
            dets.append(np.linalg.det(S))
            if previo is not None and np.array_equal(sop, previo):
                break
            previo = sop
        if dets[-1] < mejor[0]:
            mejor = (dets[-1], mu, S)
    det, mu, S = mejor
    alfa = h / n
    c = alfa / stats.chi2.cdf(stats.chi2.ppf(alfa, p), p + 2)       # factor de consistencia
    return mu, c * S, (det, mu, S)

# datos: 100 normales correlacionados y un grupo de 25 atípicos en la dirección en que los normales casi no varían
rng = np.random.default_rng(5)
normales = rng.multivariate_normal([0, 0], [[1, 0.6], [0.6, 1]], size=100)
atipicos = np.array([4.2, -4.2]) + 0.35 * rng.normal(size=(25, 2))
X = np.vstack([normales, atipicos])
corte = stats.chi2.ppf(0.975, 2)

# el teorema de los pasos C: desde un inicio cualquiera, el determinante no crece
h = int(0.75 * len(X))
idx0 = np.random.default_rng(3).choice(len(X), 3, replace=False)
mu0, S0 = X[idx0].mean(0), np.cov(X[idx0].T, bias=True)
dets = []
for _ in range(8):
    mu0, S0, _ = paso_c(X, mu0, S0, h)
    dets.append(np.linalg.det(S0))
print("determinantes tras cada paso C:", np.round(dets, 4), "| no crecen:", all(a >= b - 1e-12 for a, b in zip(dets, dets[1:])))

mu_c, S_c = X.mean(0), np.cov(X.T, bias=True)
mu_r, S_r, (det_raw, mu_raw, S_raw) = mcd(X, 0.75)
for nombre, m, S in [("clásica", mu_c, S_c), ("MCD", mu_r, S_r)]:
    d = distancias2(X, m, S)
    print(f"{nombre:8s}: atípicos detectados {(d[100:] > corte).sum():2d}/25, normales marcados {(d[:100] > corte).sum():2d}/100, media estimada {np.round(m, 2)}")

sk = MinCovDet(support_fraction=0.75, random_state=0).fit(X)
print("det MCD bruto (tuyo / scikit-learn):", round(float(det_raw), 5), "/", round(float(np.linalg.det(sk.raw_covariance_)), 5))

From a random start the determinant is 0.3982 after the first C-step and 0.3588 after the second, where it stays: the sequence does not increase, as the theorem says. With 25 outliers among 125 points (20%), the classical mean shifts to (0.92,−0.83)(0.92, -0.83) and detects none (0 of 25; flags 2 normal points), whereas MCD with h=0.75nh = 0.75n estimates mean (0.14,0.03)(0.14, 0.03) and detects all (25 of 25, without flagging a normal point). Your implementation and scikit-learn’s reach the same raw determinant, 0.35883, the minimum they find. scikit-learn uses the same scheme (with n_trials starts and a reweighting step), so in practice MinCovDet(...).fit(X).mahalanobis(X) suffices.

A limit to remember: MCD requires h>ph > p and nn substantially greater than pp for subset covariance to be invertible and stable. In high dimensions, combine it with dimension reduction or use regularized variants.

Local distance and density: k neighbors and LOF

Mahalanobis assumes one elliptical cloud. If data have several groups, or oddly shaped ones, you need a score looking only around each point. The simplest: distance to the kkth neighbor rk(x)r_k(\vb{x}). This is in fact the kk-neighbor density estimate score: p^(x)=k/(n cd rk(x)d)\hat{p}(\vb{x}) = k/(n\,c_d\,r_k(\vb{x})^d) with cdc_d the unit-ball volume, and thus −log⁡p^=dlog⁡rk+cte-\log\hat{p} = d\log r_k + \mathrm{cte}, an increasing function of rkr_k. Detecting with kkth-neighbor distance is detecting with kk-neighbor density.

We saw its limitation at the start: density is absolute, and with groups of very different density, what is unusual in one is normal in another. Breunig, Kriegel, Ng and Sander (2000) addressed this with the local outlier factor. To make it concrete, the next cell builds a compact group (150 points, standard deviation 0.15), a sparse one (100 points, standard deviation 1.2), a local outlier 0.9 from the compact group, and a global outlier far from everything, scoring both ways.

[ ]Distance to the kth neighbor versus LOFBrowser
import numpy as np
from sklearn.neighbors import NearestNeighbors, LocalOutlierFactor

rng = np.random.default_rng(2)
denso = rng.normal([0, 0], 0.15, size=(150, 2))          # grupo compacto
disperso = rng.normal([6, 0], 1.2, size=(100, 2))        # grupo disperso
o_local = np.array([[0.0, 0.9]])                          # junto al grupo denso: 6 sigmas del denso
o_global = np.array([[3.0, 6.5]])                         # lejos de todo
X = np.vstack([denso, disperso, o_local, o_global])
i_local, i_global = len(X) - 2, len(X) - 1
k = 10

dist, _ = NearestNeighbors(n_neighbors=k + 1).fit(X).kneighbors(X)
kdist = dist[:, k]                                        # distancia al k-ésimo vecino (sin contar el propio punto)
lof = -LocalOutlierFactor(n_neighbors=k).fit(X).negative_outlier_factor_

def puesto(s, i):
    return int((s > s[i]).sum()) + 1                      # 1 = el más anómalo

print(f"distancia al {k}-ésimo vecino: atípico local {kdist[i_local]:.2f} (puesto {puesto(kdist, i_local)}), "
      f"global {kdist[i_global]:.2f} (puesto {puesto(kdist, i_global)}), mediana del grupo disperso {np.median(kdist[150:250]):.2f}")
print(f"LOF:                      atípico local {lof[i_local]:.2f} (puesto {puesto(lof, i_local)}), "
      f"global {lof[i_global]:.2f} (puesto {puesto(lof, i_global)}), mediana del grupo disperso {np.median(lof[150:250]):.2f}")

# LOF es invariante a la escala; la distancia al k-ésimo vecino, no
lof10 = -LocalOutlierFactor(n_neighbors=k).fit(10 * X).negative_outlier_factor_
print("máxima diferencia de LOF al multiplicar los datos por 10:", float(np.abs(lof10 - lof).max()))

The local outlier is 0.67 from its tenth neighbor, less than the median of the sparse group (0.79): by distance it ranks 70th of 252 and cannot be flagged without flagging half the sparse group. By LOF it is first (4.61), ahead of the global outlier (3.49), and the sparse group’s median is 1.03, normal. Let us see why.

The interpretation is direct. If aa is in a region as dense as its neighbors’, their lrd values are equal and LOF⁡k(a)=1\operatorname{LOF}_k(a) = 1; if aa is much less dense than its neighbors, LOF⁡k(a)≫1\operatorname{LOF}_k(a) \gg 1. Reachability distance (with max⁡\max) smooths fluctuations: two points very close to the same neighbor are treated as if at its kdist⁡\operatorname{kdist}, preventing estimated density from exploding in accidental data clumps.

Two properties follow in one line. First, LOF is 1 if all neighbors have the same lrd as the point, by definition. Second, LOF is scale invariant: multiplying data by s>0s > 0 multiplies all distances and thus all reach⁡\operatorname{reach} by ss, divides lrd⁡\operatorname{lrd} by ss, and leaves ratios unchanged. The cell confirms this (maximum difference on multiplying by 10 is 2.7⋅10−92.7\cdot 10^{-9}, due to the 10−1010^{-10} constant scikit-learn adds for stability). Distance to the kkth neighbor, by contrast, is multiplied by ss: it is an absolute scale.

What LOF essentially measures is how many times less dense a point is than its neighborhood. Breunig and coauthors propose not fixing kk: compute LOF over a range and take the maximum, so neither small kk (which sees noise) nor kk above group size hides the anomaly. The 6-point microcluster in the zoo below illustrates this: with k≤5k \le 5 its points see only one another, are as dense as their neighbors, and their LOF is near 1. Nor is it enough for kk to exceed group size: at k=10k = 10, half the neighbors are still groupmates and LOF flags none of the 6 (at the 8% threshold); at k=20k = 20 it flags 1, and at k=40k = 40 all 6. Therefore Breunig and coauthors set the upper bound of the kk range to the maximum group size you still want to see as anomalous.

DBSCAN (density-based clustering) also provides an anomaly interpretation: noise points, those without minPts\mathrm{minPts} neighbors within distance ε\varepsilon, are outliers. It is a binary score with global ε\varepsilon (the same absolute-density limitation), whereas HDBSCAN with GLOSH scoring is local.

Isolation Forest: rare points are cheaper to isolate

Everything above estimates some density or distance: expensive in high dimensions and requiring a profile of normality. Liu, Ting and Zhou (2008) proposed the opposite: do not profile normality, isolate rarity. Take a point, randomly select a feature and a uniformly random cut value between that feature’s minimum and maximum (in the current node), and repeat in the region containing the point. An outlier lies in an empty region and is alone after few cuts; a point in a group center needs many. The number of cuts is its path length.

Why c(n)c(n)? A complete isolation tree has the structure of a decision tree with one point per leaf: nn leaves and n−1n - 1 internal nodes. It has the form of a binary search tree with n−1n - 1 keys inserted in random order, whose nn leaves (gaps between keys) have average depth 2(Hn−1)2(H_n - 1), with HnH_n the nnth harmonic number: the mean length of an unsuccessful search. Since 2(Hn−1)=2Hn−1−2(n−1)/n2(H_n - 1) = 2H_{n-1} - 2(n-1)/n and Hn−1≈ln⁡(n−1)+γH_{n-1} \approx \ln(n-1) + \gamma, we obtain the formula for c(n)c(n) (for n=2n = 2 the harmonic approximation is poor, so the exact value c(2)=2(H2−1)=1c(2) = 2(H_2 - 1) = 1 is used). This is the typical path length of a point in a set of nn points; dividing by it gives a score comparable across subsample sizes. Thus:

  • E[h]→c(ψ)\E[h] \to c(\psi) gives s→2−1=0.5s \to 2^{-1} = 0.5: the point isolates as fast as a typical one.
  • E[h]→0\E[h] \to 0 gives s→1s \to 1: it isolates immediately and is highly anomalous.
  • Large E[h]\E[h] gives s→0s \to 0: very normal.

If all points have s≈0.5s \approx 0.5, there are no clear anomalies.

A rarely stated caveat: c(n)c(n) is exact for a binary search tree (uniform cuts by rank), but an isolation-tree cut is uniform by value, not rank: it falls in a gap between consecutive points with probability proportional to gap width. With uniform one-dimensional data gaps are exchangeable and the selected gap is uniform, so the two coincide; with bell-shaped data, wide gaps are in the tails and they do not. The cell measures mean leaf depth of isolation trees without a height limit:

[ ]How long is the average path? c(n) versus simulationBrowser
import numpy as np

def c_fn(n):
    """c(n) = 2 (ln(n - 1) + gamma) - 2 (n - 1) / n, con gamma la constante de Euler."""
    return 0.0 if n <= 1 else 2 * (np.log(n - 1) + np.euler_gamma) - 2 * (n - 1) / n

def profundidades(X, rng):
    """Profundidad media de las hojas de un árbol de aislamiento sin límite de altura (una hoja por punto)."""
    out = []
    def partir(idx, d):
        if len(idx) == 1:
            out.append(d)
            return
        P = X[idx]
        lo, hi = P.min(0), P.max(0)
        a = rng.choice(np.where(hi > lo)[0])
        v = rng.uniform(lo[a], hi[a])
        m = P[:, a] < v
        partir(idx[m], d + 1)
        partir(idx[~m], d + 1)
    partir(np.arange(len(X)), 0)
    return np.mean(out)

rng = np.random.default_rng(0)
print(" n     c(n)   uniforme 1D   normal 1D   normal 2D")
for n in (16, 64, 256):
    fila = []
    for gen in (lambda n: rng.uniform(size=(n, 1)), lambda n: rng.normal(size=(n, 1)), lambda n: rng.normal(size=(n, 2))):
        fila.append(np.mean([profundidades(gen(n), rng) for _ in range(30)]))
    print(f"{n:3d}  {c_fn(n):7.3f}  {fila[0]:11.3f}  {fila[1]:10.3f}  {fila[2]:10.3f}")

With uniform one-dimensional data the simulation (10.219 for n=256n = 256) reproduces c(256)=10.245c(256) = 10.245; with normal data mean depth is larger (11.574 in 1D and 11.779 in 2D): value-uniform cuts often land in wide tail gaps, separate one or two points, and leave the central block nearly intact, requiring more cuts. Thus c(n)c(n) is a reasonable normalization, not an exact expectation, and ss should be read as an ordinal scale with 0.5 an approximate reference: with bell-shaped data a typical point has ss somewhat below 0.5.

Why small subsamples. With ψ=256\psi = 256 (the original proposal’s default and scikit-learn’s max_samples='auto', using min⁡(256,n)\min(256, n)), the forest does not see all data in each tree. This reduces cost (each tree is small: training costs O(Tψlog⁡ψ)O(T\psi\log\psi), independent of nn, and scoring a point O(Tlog⁡ψ)O(T\log\psi)) and combats masking and swamping: with few points, an anomaly group lacks enough mass to look normal or hide its neighbors. You will see this in the zoo (8% threshold): with ψ=64\psi = 64 the forest flags all 6 microcluster points; with ψ=256\psi = 256, only 3.

See how a path is built and what happens to the score.

InteractiveRare points are cheaper to isolate
Tree 8: 5 cuts; 1 subsample point remains in the region
leaf: 1 point, h = 5.00
Path length h(x)h(x) across 100 trees
051015202502468101214path length
Score s(x)s(x) on the plane: from 0.38 (light) to 0.77 (intense)
  • selected point (and its path)
  • comparison point
  • tree subsample (filled circles; hollow = outside)
  • region surviving the cuts
8 of 100
64
cut 5 of 5
Tree 8: depth · leaf · h(x)h(x)5 · 1 · 5.00
E[h]E[h] for this point (outlier) across 100 trees4.03
c(ψ)c(\psi)7.47
Score s(x)s(x) for this point0.688
Comparison point score0.385 (E[h] = 10.29)
Random cuts isolate the unusual point sooner: small E[h]E[h], large ss.
126 points: 120 normal (Gaussian with standard deviation 0.8) and 6 outliers. Left, the actual path of the selected point (orange circle) through tree tt of a 100-tree forest: each random cut is a line, the orange region survives, and filled circles are that tree's subsample points. Initially tree 8 isolates outlier (3.1, 2.3) in 5 cuts. Press play to see them one at a time and change trees: some isolate it in 1 or 2 cuts, others in 6. Center, histogram of the outlier's 100 path lengths (orange) and the most central point's (dashed gray): with ψ=64\psi = 64 means are 4.03 and 10.29, and scores ss are 0.688 and 0.385. Right, s(x)s(\vb{x}) across the plane: straight bands reveal axis-parallel cuts. Raise ψ\psi to 126 (all points): means become 4.29 and 12.57. Click any point to see its path and compare.

Geometric limitation. Since every cut is axis-parallel, the forest sees correlations poorly: a point outside a diagonal cloud without leaving any feature’s range isolates almost as slowly as a normal point. The straight bands above are the signature of these cuts. The cell measures this on a cloud with correlation 0.95:

[ ]Isolation Forest versus a broken correlationBrowser
import numpy as np
from sklearn.ensemble import IsolationForest

rng = np.random.default_rng(0)
X = rng.multivariate_normal([0, 0], [[1, 0.95], [0.95, 1]], size=1000)
bosque = IsolationForest(random_state=0).fit(X)
S_inv = np.linalg.inv(np.cov(X.T))
puntos = {"(0, 0), el centro": [0, 0], "(2, 2), sobre la diagonal": [2, 2], "(1, -1), fuera de la diagonal": [1, -1]}
s_datos = -bosque.score_samples(X)
print("percentiles 90 y 99 de s en los datos:", np.round(np.quantile(s_datos, [0.9, 0.99]), 3))
for nombre, x in puntos.items():
    x = np.array(x, dtype=float)
    print(f"{nombre:30s} s = {-bosque.score_samples(x[None])[0]:.3f}   d² de Mahalanobis = {x @ S_inv @ x:5.1f}")

Point (1,−1)(1, -1) has d2=41.6d^2 = 41.6 (the 99.9% threshold of a χ22\chi^2_2 is 13.8), but the forest gives it s=0.592s = 0.592, almost the same as (2,2)(2, 2), a normal diagonal point (d2=3.9d^2 = 3.9, s=0.581s = 0.581), and below the data’s own 99th percentile (0.700): alerting on the rarest 1% misses it. Each feature separately is perfectly normal at that point, and cuts examine features separately. Extended Isolation Forest (Hariri, Carrasco Kind and Brunner, 2021) cuts with randomly directed hyperplanes to reduce these artifacts; this lesson covers only the original. The benchmark’s subspace scenario confirms this in eight dimensions.

Lab: Isolation Forest and LOF from scratch

Implement both methods with NumPy and compare with scikit-learn on a dataset with two groups of different density, 12 global outliers and a 6-point microcluster (18 anomalies among 258). Isolation Forest is random, so do not expect scores to match scikit-learn’s: the honest comparison is against variation between two scikit-learn seeds. LOF should match.

[ ]Isolation Forest and LOF from scratch versus scikit-learnBrowser
import numpy as np
from scipy.stats import spearmanr
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
from sklearn.metrics import average_precision_score

# --- Isolation Forest desde cero ---------------------------------------------------------
def c_fn(n):
    return 0.0 if n <= 1 else 2 * (np.log(n - 1) + np.euler_gamma) - 2 * (n - 1) / n

def construir(X, idx, prof, max_prof, rng):
    """Árbol de aislamiento: corte uniforme en una variable al azar hasta aislar o llegar a max_prof."""
    if prof >= max_prof or len(idx) <= 1:
        return ("hoja", len(idx))
    P = X[idx]
    lo, hi = P.min(0), P.max(0)
    cand = np.where(hi > lo)[0]
    if len(cand) == 0:
        return ("hoja", len(idx))
    a = rng.choice(cand)
    v = rng.uniform(lo[a], hi[a])
    m = P[:, a] < v
    return ("nodo", a, v, construir(X, idx[m], prof + 1, max_prof, rng), construir(X, idx[~m], prof + 1, max_prof, rng))

def recorrer(nodo, X, filas, prof, h):
    """Suma a h[filas] la longitud de camino h(x) = profundidad + c(tamaño de la hoja)."""
    if len(filas) == 0:
        return
    if nodo[0] == "hoja":
        h[filas] += prof + c_fn(nodo[1])
        return
    _, a, v, izq, der = nodo
    m = X[filas, a] < v
    recorrer(izq, X, filas[m], prof + 1, h)
    recorrer(der, X, filas[~m], prof + 1, h)

class BosqueAislamiento:
    def __init__(self, n_arboles=100, psi=256, seed=0):
        self.T, self.psi, self.seed = n_arboles, psi, seed

    def fit(self, X):
        rng = np.random.default_rng(self.seed)
        self.psi_ = min(self.psi, len(X))
        max_prof = int(np.ceil(np.log2(self.psi_)))
        self.arboles = [construir(X, rng.choice(len(X), self.psi_, replace=False), 0, max_prof, rng) for _ in range(self.T)]
        return self

    def score_samples(self, X):
        h = np.zeros(len(X))
        for t in self.arboles:
            recorrer(t, X, np.arange(len(X)), 0, h)
        return 2 ** (-(h / self.T) / c_fn(self.psi_))        # s(x) = 2^(-E[h]/c(psi)), mayor = más anómalo

# --- LOF desde cero ----------------------------------------------------------------------
def lof_scores(X, k):
    n = len(X)
    D = np.sqrt(((X[:, None, :] - X[None, :, :]) ** 2).sum(-1))
    np.fill_diagonal(D, np.inf)                                # un punto no es vecino de sí mismo
    vec = np.argsort(D, axis=1)[:, :k]                         # N_k(a)
    filas = np.arange(n)[:, None]
    kdist = D[np.arange(n), vec[:, -1]]                        # distancia al k-ésimo vecino
    alcance = np.maximum(kdist[vec], D[filas, vec])            # reach-dist_k(a, b) = max{kdist(b), d(a, b)}
    lrd = 1.0 / (alcance.mean(axis=1) + 1e-10)                 # densidad de alcanzabilidad local
    return lrd[vec].mean(axis=1) / lrd                         # media de lrd(b) / lrd(a)

# --- datos: dos grupos de densidad distinta, 12 atípicos globales y un microgrupo de 6 ----
rng = np.random.default_rng(7)
X = np.vstack([
    rng.normal([-1.7, 0.2], 0.28, size=(110, 2)),
    rng.normal([1.8, 0.4], [1.0, 0.45], size=(130, 2)),
    rng.uniform([-4.4, -3.2], [4.4, 3.2], size=(12, 2)),
    rng.normal([0.2, -2.4], 0.07, size=(6, 2)),
])
y = np.r_[np.zeros(240), np.ones(18)].astype(bool)

lof_mio = lof_scores(X, 20)
lof_sk = -LocalOutlierFactor(n_neighbors=20).fit(X).negative_outlier_factor_
print(f"LOF: máxima diferencia con scikit-learn = {np.abs(lof_mio - lof_sk).max():.1e}")

s_mio = BosqueAislamiento(100, 256, seed=0).fit(X).score_samples(X)
a = -IsolationForest(n_estimators=100, max_samples=256, random_state=0).fit(X).score_samples(X)
b = -IsolationForest(n_estimators=100, max_samples=256, random_state=1).fit(X).score_samples(X)
print(f"Isolation Forest: Spearman tuyo-scikit-learn = {spearmanr(s_mio, a)[0]:.3f}; entre dos semillas de scikit-learn = {spearmanr(a, b)[0]:.3f}")
print(f"PR-AUC: tuyo {average_precision_score(y, s_mio):.3f}, scikit-learn {average_precision_score(y, a):.3f}; LOF(k=20) {average_precision_score(y, lof_mio):.3f}")
print("rango de s(x):", round(float(s_mio.min()), 3), "a", round(float(s_mio.max()), 3), "| mediana", round(float(np.median(s_mio)), 3))

Your LOF and scikit-learn’s agree to 1.8⋅10−151.8\cdot10^{-15}. Your Isolation Forest and scikit-learn’s have Spearman rank correlation 0.978, higher than between two scikit-learn seeds (0.965): your forest is indistinguishable from the library’s within the method’s own noise. PR-AUC values are 0.848 (yours) and 0.853 (scikit-learn), and LOF with k=20k = 20 gives 0.917. Isolation Forest scores range from 0.373 to 0.785 with median 0.431: none approaches 1, and more than half the data lie below 0.5 because, as the c(n)c(n) cell showed, with bell-shaped data actual mean path length exceeds c(ψ)c(\psi). Thus 0.5 is not a universal threshold; set it by quantile or budget.

Support boundary: One-Class SVM and SVDD

Full density may be too much to ask. If you only care whether a point lies inside the region where almost everything lives, estimate that region, a level set of pp. This is what Schölkopf, Platt, Shawe-Taylor, Smola and Williamson’s (2001) One-Class SVM does: it separates data from the origin in kernel feature space using a maximum-margin hyperplane, allowing a fraction ν\nu of points on the other side.

The most useful part of the dual is what optimality (KKT) conditions say: αi=0\alpha_i = 0 implies f(xi)≥0f(\vb{x}_i) \ge 0 (inside); αi=1νn\alpha_i = \frac{1}{\nu n} implies f(xi)≤0f(\vb{x}_i) \le 0 (on the boundary or outside) and ξi≥0\xi_i \ge 0; and 0<αi<1νn0 < \alpha_i < \frac{1}{\nu n} implies f(xi)=0f(\vb{x}_i) = 0 (on the boundary). The property giving the parameter meaning follows.

Proof

(a) If f(xi)<0f(\vb{x}_i) < 0, constraint ⟨w,ϕ(xi)⟩≥ρ−ξi\inner{\vb{w}}{\phi(\vb{x}_i)} \ge \rho - \xi_i forces ξi>0\xi_i > 0, and complementary slackness αi(…)\alpha_i(\ldots) and the bound condition (the multiplier of ξi≥0\xi_i \ge 0 is 1νn−αi\frac{1}{\nu n} - \alpha_i) give αi=1νn\alpha_i = \frac{1}{\nu n}. Since ∑iαi=1\sum_i\alpha_i = 1, at most νn\nu n indices can equal 1νn\frac{1}{\nu n}. (b) Each αi\alpha_i is at most 1νn\frac{1}{\nu n} and they sum to 1, so at least νn\nu n indices with αi>0\alpha_i > 0 are needed. ■\blacksquare

∎

With the RBF kernel, k(x,x)=1k(\vb{x}, \vb{x}) = 1 for every x\vb{x} and One-Class SVM is equivalent to the smallest sphere enclosing data in feature space with penalized slack (SVDD, support vector data description, Tax and Duin, 2004). The reason fits in a line: since ∥ϕ(x)∥=1\norm{\phi(\vb{x})} = 1, ∥ϕ(x)−w∥2=1−2⟨w,ϕ(x)⟩+∥w∥2\norm{\phi(\vb{x}) - \vb{w}}^2 = 1 - 2\inner{\vb{w}}{\phi(\vb{x})} + \norm{\vb{w}}^2, so being on the good side of the hyperplane, ⟨w,ϕ(x)⟩≥ρ\inner{\vb{w}}{\phi(\vb{x})} \ge \rho, is equivalent to being inside the ball centered at w\vb{w} with squared radius 1+∥w∥2−2ρ1 + \norm{\vb{w}}^2 - 2\rho. That is why the detector estimates a level set, not a density: its boundary depends on support vectors, the most extreme points, and on γ\gamma (kernel width, k=e−γ∥x−x′∥2k = e^{-\gamma\norm{\vb{x} - \vb{x}'}^2}), setting the scale. Check the ν\nu property with scikit-learn:

[ ]The ν property: outside ≤ ν ≤ support vectorsBrowser
import numpy as np
from sklearn.svm import OneClassSVM

rng = np.random.default_rng(4)
X = np.vstack([rng.normal(0, 1, size=(300, 2)), rng.normal([3, 3], 0.6, size=(200, 2))])
n = len(X)
print("  nu   fracción fuera (f<0)   nu   fracción de vectores soporte")
for nu in (0.02, 0.05, 0.1, 0.2, 0.4):
    m = OneClassSVM(kernel="rbf", gamma=0.3, nu=nu, tol=1e-8).fit(X)
    fuera = (m.decision_function(X) < -1e-6).mean()
    sv = len(m.support_) / n
    print(f"{nu:5.2f}   {fuera:8.3f}   <= {nu:4.2f} <=   {sv:8.3f}")

# dual en la normalización de scikit-learn: sum(alfa) = nu n, 0 <= alfa <= 1
m = OneClassSVM(kernel="rbf", gamma=0.3, nu=0.1, tol=1e-8).fit(X)
alfa = m.dual_coef_.ravel()
print("suma de alfa:", round(float(alfa.sum()), 3), "= nu n =", 0.1 * n, "| máximo:", round(float(alfa.max()), 3))
print("vectores soporte en la cota (alfa = 1):", int((alfa > 1 - 1e-8).sum()), "| libres:", int(((alfa > 1e-8) & (alfa < 1 - 1e-8)).sum()))

In all five rows the fraction with f<0f < 0 is at most ν\nu and the support-vector fraction at least as large (with ν=0.1\nu = 0.1: 0.082 and 0.114). scikit-learn normalizes the dual with ∑αi=νn\sum\alpha_i = \nu n and 0≤αi≤10 \le \alpha_i \le 1, the same problem multiplied by νn\nu n: the α\alpha sum is exactly 50 =νn= \nu n and the maximum is 1. Of 57 support vectors, 41 are at the bound (paying slack) and 16 are free (on the boundary).

Two important nuances. First, ν\nu bounds the training fraction outside the boundary, not the future false-alarm rate, although for large nn and under kernel and distribution conditions the fractions converge to ν\nu (Schölkopf and coauthors, 2001). Second, the method is not scale invariant: γ\gamma uses data units. The zoo figure shows that large γ\gamma makes the boundary hug each point, while small γ\gamma makes it resemble an ellipse.

Reconstruction error: PCA and beyond

Another definition of “normal” is what can be reconstructed by a low-dimensional model. If normal data lie near a subspace, a point whose projection loses much lies somewhere the model cannot explain. This is the PCA reconstruction view: the kk-dimensional subspace minimizing mean squared reconstruction error.

What does QQ see that Mahalanobis does not, and vice versa? There is an exact decomposition. With y=V⊤(x−μ^)\vb{y} = \mat{V}\T(\vb{x} - \hat{\vb{\mu}}) the principal-component coordinates:

d2(x)=∑j≤kyj2λj⏟Tk2 (inside the subspace)+∑j>kyj2λj,Qk(x)=∑j>kyj2.d^2(\vb{x}) = \underbrace{\sum_{j \le k}\frac{y_j^2}{\lambda_j}}_{T^2_k\ \text{(inside the subspace)}} + \sum_{j > k}\frac{y_j^2}{\lambda_j}, \qquad Q_k(\vb{x}) = \sum_{j > k} y_j^2 .

The first equality is the definition of d2d^2 in the eigenbasis; the second follows because projection onto the orthogonal complement has coordinates yjy_j with j>kj > k and the basis is orthonormal. Two immediate readings:

  • Tk2T^2_k (Hotelling’s subspace T2T^2) detects anomalies inside the subspace: points far along principal directions that QQ does not see because residual is small.
  • QkQ_k weights residual uniformly and d2d^2 weights it by 1/λj1/\lambda_j. With very small λj\lambda_j (directions with almost no variance), Mahalanobis greatly amplifies any deviation; QQ does not. If data have substantial isotropic noise in those directions, Mahalanobis dilutes the signal among many noise components, whereas QQ with well-chosen kk sums only the residual.

If x\vb{x} is Gaussian and mean and covariance are the true ones, Tk2∼χk2T^2_k \sim \chi^2_k and the residual part of d2d^2 is χp−k2\chi^2_{p-k}, independent of it; by contrast, Qk=∑j>kλjzj2Q_k = \sum_{j>k}\lambda_j z_j^2 is a weighted combination of χ12\chi^2_1 variables, not a χ2\chi^2, so its threshold is approximated (Jackson and Mudholkar, 1979, give a classic approximation) or calibrated empirically. The next figure uses the one-dimensional threshold λ2 χ1,0.9752\lambda_2\,\chi^2_{1,0.975}, exact for k=p−1k = p - 1.

InteractiveTwo ways to deviate
Principal line, reconstruction band (97.5%) and Mahalanobis ellipse (97.5%)
Q = 0.00
  • first component
  • band Q≤λ2χ1,0.9752Q \le \lambda_2\chi^2_{1,0.975}
  • ellipse d2≤χ2,0.9752d^2 \le \chi^2_{2,0.975}
  • normal points
  • contaminants
0
T2=y12/λ1T^2 = y_1^2/\lambda_1 (along the axis)9.19
Q=y22Q = y_2^2 (reconstruction error)0.00
d2=T2+y22/λ2d^2 = T^2 + y_2^2/\lambda_2 (threshold 7.38)9.2
Flagged normal points: ellipse · band5 · 3 of 140
Mahalanobis flags it but reconstruction does not: the point is on the principal subspace but far along it (large T², small Q).
140 normal points along a line at 30° (standard deviation 1.6 along it and 0.25 perpendicular) and, if you increase mm, up to 40 contaminants (red) displaced 3 units perpendicular. Drag the magenta point: the orange line is the first component, pink band is Q≤λ2χ1,0.9752Q \le \lambda_2\chi^2_{1,0.975} and dashed blue ellipse is d2≤χ2,0.9752d^2 \le \chi^2_{2,0.975}. Readouts decompose position into T2T^2 (along the line), QQ (pink segment) and d2d^2. Initially the point 5.2 units along the line has Q≈0Q \approx 0 and is flagged only by the ellipse (extreme but coherent). With the 'near center, off line' button, the point lands at the line's center and is flagged by the band but not the ellipse. Raise mm to 10 with classical PCA: contaminants rotate the first component from 31° to 25° and inflate λ2\lambda_2; at m=40m = 40 it is at 2° and reconstruction detects no contaminants. Enable robust estimation (MCD) and the component remains at 31°: all 40 are detected.

The next cell repeats the lesson in 10 dimensions, with normal data in a 3-dimensional subspace plus noise of standard deviation 0.1. There are two anomaly types (20 of each against 580 normal): A, extremes inside the subspace (scale ×3), and B, deviations outside the subspace (noise standard deviation 0.8). Training is then contaminated and classical PCA compared with PCA computed using MCD covariance.

[ ]T², Q and Mahalanobis in 10 dimensions, and contaminationBrowser
import numpy as np
from sklearn.covariance import MinCovDet
from sklearn.metrics import average_precision_score

rng = np.random.default_rng(3)
p, k = 10, 3
A = np.linalg.qr(rng.normal(size=(p, k)))[0] * np.array([3.0, 2.0, 1.5])     # base de un subespacio de dimensión 3
def normales(n, escala=1.0):
    return escala * rng.normal(size=(n, k)) @ A.T + 0.1 * rng.normal(size=(n, p))

Xn = normales(600)
# tipo A: extremos dentro del subespacio; tipo B: fuera del subespacio con amplitud moderada
Xa = normales(20, escala=3.0)
ruido = rng.normal(size=(20, p))
Q0 = np.eye(p) - np.linalg.qr(A)[0] @ np.linalg.qr(A)[0].T                    # proyector sobre el complemento ortogonal
Xb = normales(20) + 0.8 * ruido @ Q0

def ajusta_pca(X, k):
    mu = X.mean(0)
    U, s, Vt = np.linalg.svd(X - mu, full_matrices=False)
    return mu, Vt, (s ** 2) / len(X)

def puntuaciones(X, mu, Vt, lam, k):
    Y = (X - mu) @ Vt.T
    T2 = (Y[:, :k] ** 2 / lam[:k]).sum(1)
    Q = (Y[:, k:] ** 2).sum(1)
    d2 = (Y ** 2 / lam).sum(1)
    return {"T2 (dentro)": T2, "Q (reconstrucción)": Q, "Mahalanobis": d2}

mu, Vt, lam = ajusta_pca(Xn, k)
print("PR-AUC por tipo de anomalía (580 normales + 20 anomalías):")
for nombre, Xa_ in (("A: extremo en el subespacio", Xa), ("B: fuera del subespacio", Xb)):
    Z = np.vstack([normales(580), Xa_])
    y = np.r_[np.zeros(580), np.ones(20)].astype(bool)
    sc = puntuaciones(Z, mu, Vt, lam, k)
    print(f"  {nombre:30s}", {n: round(float(average_precision_score(y, s)), 2) for n, s in sc.items()})

# contaminación: 15 % de los datos de entrenamiento se salen del subespacio en una sola dirección
u = Q0 @ rng.normal(size=p)
u /= np.linalg.norm(u)
Xc = np.vstack([normales(510), normales(90) + 4.0 * rng.normal(size=(90, 1)) * u])
Z = np.vstack([normales(580), Xb])
y = np.r_[np.zeros(580), np.ones(20)].astype(bool)
mu1, Vt1, lam1 = ajusta_pca(Xc, k)
mcd = MinCovDet(support_fraction=0.8, random_state=0).fit(Xc)
w, V = np.linalg.eigh(mcd.covariance_)
w, V = w[::-1], V[:, ::-1]
for nombre, (m_, V_, l_) in {"PCA clásica": (mu1, Vt1, lam1), "PCA con covarianza MCD": (mcd.location_, V.T, w)}.items():
    Q = puntuaciones(Z, m_, V_, l_, k)["Q (reconstrucción)"]
    print(f"con 15 % de contaminación, {nombre:24s}: PR-AUC de Q = {average_precision_score(y, Q):.2f}")

For type A anomalies (extremes within the subspace), T2T^2 obtains PR-AUC 0.83 and Mahalanobis 0.71, while QQ obtains 0.04: it cannot see them because their residual is normal. For type B (outside the subspace), QQ and Mahalanobis reach 1.00 and T2T^2 stays at 0.03. Notice Mahalanobis (0.71) performs worse than T2T^2 on type A: it adds seven noise terms to T2T^2, increasing score variance. Contamination is lethal without careful estimation: with 15% of training data displaced in a direction outside the subspace, classical PCA learns that direction as normal (QQ PR-AUC = 0.17), whereas using MCD covariance to obtain the basis solves it (1.00). This is the same masking as before in reconstruction language.

The preceding lesson’s robust PCA attacks the problem differently: decompose X=L+S\mat{X} = \mat{L} + \mat{S} with low-rank L\mat{L} and sparse S\mat{S}, and S\mat{S} exposes anomalous cells, not just rows. In the nonlinear limit an autoencoder replaces the subspace with a learned manifold: the score remains reconstruction error. An over-capacity autoencoder can learn to reconstruct anomalies too (Ruff and coauthors, 2021, discuss this), and it trains on the same contaminated data; latent representations revisit this.

The detector zoo

You now have all eight detectors. This figure puts them on the same cloud of 260 points with 20 anomalies of four types: 12 global, 2 local near the dense group, 6 in a microcluster, and of course two normal groups of differing density. It is the only place in the lesson where you see each detector’s blind spot.

InteractiveThe detector zoo
260 points with 20 anomalies. Background: score percentile. Line: threshold.
dense groupsparse group
  • normal (dense)
  • normal (sparse)
  • global
  • local
  • microcluster
  • flagged (solid ring); unflagged anomaly (dashed)
10
8 %
Average precision (PR-AUC)0.784
ROC-AUC0.969
Precision at k=20k = 2065 %
Flagged / true anomalies21 / 20
Global · local · microcluster detected11/12 · 2/2 · 0/6
It compares each point with its neighbors’ density: with k=10k = 10 it detects local outliers beside the dense group that distance and ellipse miss, but not the microcluster (its neighbors are equally dense). With k=40k = 40 it detects both; with k=1k = 1 it is almost useless.
260 points (110 in a dense group, 130 in a sparse elongated one, 12 global outliers, 2 local and a 6-point microcluster) and a score map for the selected detector: color is score percentile among training points and the black line the threshold flagging the 'assumed contamination' fraction. Flagged points have solid rings; missed anomalies have dashed rings. Readouts show PR-AUC, ROC-AUC, precision at k=20k = 20 and how many anomalies of each type are detected. Initially (LOF with k=10k = 10, 8% threshold): PR-AUC 0.784, detects both local outliers (which neither Mahalanobis nor kkth-neighbor distance sees) but none of the 6 microcluster points. Raise kk to 40 to detect all. With kkth-neighbor distance the reverse happens: k=10k = 10 detects the microcluster and not the locals. Try GMM with 4 components (one captures the microcluster), Isolation Forest with ψ=64\psi = 64 versus 256, and One-Class SVM with γ=4\gamma = 4.

Read this as a risk map, not a ranking. No detector wins on every front: LOF with small kk sees local but not collective anomalies; distance to the kk neighbors the reverse; Mahalanobis (classical or robust) sees global anomalies well provided normal data form one cloud; Isolation Forest is good with few relevant features but confounded by correlations; One-Class SVM requires choosing γ\gamma and ν\nu with consistently scaled data; density scores need one bandwidth or a reasonable KK. The next lab measures this.

Evaluating an anomaly detector

Evaluating an anomaly detector without labels is impossible; with labels (whatever you have for validation, even if not used for training), three things need care.

1. ROC can mislead at low prevalence. The ROC curve plots true-positive rate (recall) against false-positive rate at all thresholds; its area is the probability that an anomaly scores above a normal point. Both rates are conditional on class: they do not depend on how many normal points there are. But what matters is not false-positive rate alone; it is how many alerts are real.

This is Bayes’ theorem with a two-case partition. Two consequences: ROC does not depend on π\pi (because TPR and FPR do not), but precision does. PR-curve area inherits this dependence. A typical case is “good” detectors with tiny prevalence. With TPR = 0.99 and FPR = 0.01 (99% sensitivity and specificity), prevalence π=10−4\pi = 10^{-4} yields precision 0.99⋅10−40.99⋅10−4+0.9999⋅0.01≈0.0098\frac{0.99\cdot10^{-4}}{0.99\cdot10^{-4} + 0.9999\cdot 0.01} \approx 0.0098: one alert in a hundred is real. The cell simulates such a binormal detector (N(0,1)\Normal(0,1) scores for normals and N(d,1)\Normal(d, 1) for anomalies, with d=2 z0.99d = 2\,z_{0.99}) on 500,000 points:

[ ]The same ROC at four prevalencesBrowser
import numpy as np
from scipy.stats import norm
from sklearn.metrics import average_precision_score, roc_auc_score

# detector binormal: puntuación N(0, 1) en normales y N(d, 1) en anomalías, con d tal que sensibilidad y
# especificidad valen 0.99 en el umbral d / 2
d = 2 * norm.ppf(0.99)
tau = d / 2
tpr, fpr = norm.sf(tau - d), norm.sf(tau)
print(f"d = {d:.3f}; TPR = {tpr:.3f}; FPR = {fpr:.3f}; ROC-AUC teórica = {norm.cdf(d / np.sqrt(2)):.4f}")

rng = np.random.default_rng(0)
N = 500_000
print("  prevalencia   anomalías   ROC-AUC    PR-AUC   precisión en tau (simulada / Bayes)   precisión en k")
for pi in (0.1, 0.01, 0.001, 0.0001):
    m = int(round(N * pi))
    s = np.r_[rng.normal(0, 1, N - m), rng.normal(d, 1, m)]
    y = np.r_[np.zeros(N - m), np.ones(m)].astype(bool)
    alerta = s > tau
    prec = (alerta & y).sum() / alerta.sum()
    bayes = pi * tpr / (pi * tpr + (1 - pi) * fpr)
    top = np.argsort(-s)[:m]
    print(f"{pi:12.4f} {m:10d}   {roc_auc_score(y, s):.4f}   {average_precision_score(y, s):.4f}   {prec:.4f} / {bayes:.4f}"
          f"                    {y[top].mean():.3f}")

ROC-AUC barely moves (0.9994 to 0.9998 across four prevalences; theory is 0.9995), but precision at the operating threshold falls from 0.916 at π=0.1\pi = 0.1 to 0.497, 0.0895 and 0.0098 at π=10−4\pi = 10^{-4}, Bayes’ formula to three digits. PR-AUC falls from 0.9965 to 0.8009 (only 50 anomalies in the last case make this noisy; the theoretical value computed by the next figure is 0.787), and precision at kk from 0.973 to 0.760. A nuance in the figure: the detector is not bad; that operating point is useless at that prevalence. Raising the threshold, the PR curve shows operating points with much higher precision and lower recall. The base-rate fallacy lies in reading “99% and 99%” without prevalence, not in the detector.

InteractiveThe base-rate fallacy
ROC curve (independent of prevalence)
000.20.20.40.40.60.60.80.811tasa de falsos positivossensibilidad
PR curve (depends on prevalence)
000.20.20.40.40.60.60.80.811sensibilidad (recall)precisiónazar: precisión = π
400 alerts: 200 true (red) and 200 false
  • ROC
  • PR
  • operating point
  • true alert
  • false alarm
1.0 %
99.0 %
4.65
Specificity (1 − FPR)99.00 %
ROC-AUC (independent of π\pi)0.9995
PR-AUC (average precision)0.9767
Precision at operating point50.0 %
Per 100,000 events: alerts · true1980 · 990
False alarms per true alert1.00
With π=1.0 %\pi = 1.0\,\% precision is already 50 %. Keep lowering π\pi: ROC does not change, but PR does.
A binormal detector: N(0,1)\Normal(0, 1) scores for normals and N(d,1)\Normal(d, 1) for anomalies. With d=4.65d = 4.65 and operating point 99% sensitivity, specificity is 99%. Left: ROC, independent of prevalence. Center: PR curve, which depends on it; dashed line is chance level π\pi. Right: 400 alerts, real ones red, in Bayes-theorem proportions. Initially π=1 %\pi = 1\,\% and half the alerts are real. Lower prevalence to 0.01% (or press 'Prevalence 1 in 10,000'): ROC does not move, operating-point precision falls to 0.98%, and the analyst receives about 100 false alerts per real one. PR-AUC falls less than point precision because other thresholds work. Lower dd to 2: now the detector is mediocre and PR-AUC also collapses. Readouts give alert and real counts per 100,000 events and false alarms per real alert.

Base-rate fallacy and data drift

Axelsson (2000) applied this argument to intrusion detection: with realistic attack prevalence in traffic, the limiting factor is suppressing false alarms, not detecting attacks; useful alerts require false-positive rates orders of magnitude lower than those achieved. For design, more sensitivity does not fix it (it increases the numerator and barely affects the denominator); what changes the result is lower FPR, by adding context, aggregating alerts by entity or incident, or using the score to prioritize (precision at kk) rather than decide.

There are two other traps. First is drift: a threshold fitted on January data no longer means the same in June because normal behavior’s distribution changes (season, product, user behavior). The usual consequence is an alert flood; monitor the score distribution (median and high quantiles) and retrain on recent windows, taking care not to include incidents. Second is an adaptive attacker: an anomaly detector characterizes what is usual, and an attacker can learn and resemble it; in security a statistical anomaly is not the same as an attack (out-of-distribution detection and data poisoning).

Finally, validation. Campos, Zimek, Sander and coauthors (2016) study how unsupervised detectors are evaluated and why conclusions depend on datasets and how they are converted into anomaly problems (for example, subsampling a class in a classification problem): an anomaly defined as “a rare class” is not necessarily geometrically anomalous. The same applies to the next lab, measuring eight detectors on synthetic data with four anomaly types and on handwritten digits with one class playing the anomaly.

Lab: an eight-detector benchmark

The benchmark uses the lesson’s eight detectors with default hyperparameters, without tuning (on standardized data): Mahalanobis, MCD, 3-component GMM, KDE with Scott’s rule, tenth-neighbor distance, LOF with k=20k = 20, 100-tree Isolation Forest, and One-Class SVM with γ\gamma scale and ν=0.05\nu = 0.05. Four synthetic scenarios have 300 points with 5% anomalies (global scattered anomalies, local near a dense group, clustered in a 15-point microcluster, and in a subspace: normal data on a plane in R8\R^8 and anomalies breaking correlation); a digits scenario (load_digits, reduced to 10 components by unlabeled PCA) uses one class as anomalies (15 of 300), with three classes playing that role. Each synthetic scenario is repeated with three seeds and each digit class with two.

[ ]Benchmark: definitionsBrowser
import time
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.covariance import EmpiricalCovariance, MinCovDet
from sklearn.mixture import GaussianMixture
from sklearn.neighbors import KernelDensity, NearestNeighbors, LocalOutlierFactor
from sklearn.ensemble import IsolationForest
from sklearn.svm import OneClassSVM
from sklearn.metrics import average_precision_score

def escenario(nombre, rng, n=300, contam=0.05):
    """Devuelve (X, y) con y = True en las anomalías. Cuatro tipos de anomalía."""
    m = max(2, int(round(contam * n)))
    n0 = n - m
    if nombre == "globales":              # dos grupos y atípicos dispersos por todo el recuadro
        N = np.vstack([rng.normal([-2, 0], 0.7, size=(n0 // 2, 2)), rng.normal([2, 0], 0.7, size=(n0 - n0 // 2, 2))])
        A = rng.uniform([-6, -5], [6, 5], size=(m, 2))
    elif nombre == "locales":             # grupo denso y grupo disperso; anomalías en un anillo junto al denso
        N = np.vstack([rng.normal([0, 0], 0.25, size=(n0 // 2, 2)), rng.normal([6, 0], 1.5, size=(n0 - n0 // 2, 2))])
        ang = rng.uniform(0, 2 * np.pi, m)
        A = np.c_[1.3 * np.cos(ang), 1.3 * np.sin(ang)] + rng.normal(0, 0.1, size=(m, 2))
    elif nombre == "agrupadas":           # las anomalías forman un grupo pequeño y compacto
        N = rng.normal(0, 1, size=(n0, 2))
        A = rng.normal([3.5, 0], 0.15, size=(m, 2))
    else:                                 # "subespacio": normales sobre un plano de R^8; anomalías con ruido fuera de él
        B = np.linalg.qr(rng.normal(size=(8, 2)))[0]
        N = rng.normal(size=(n0, 2)) @ (B * [2.0, 1.5]).T + 0.1 * rng.normal(size=(n0, 8))
        A = rng.normal(size=(m, 2)) @ (B * [2.0, 1.5]).T + 0.1 * rng.normal(size=(m, 8)) + 0.7 * rng.normal(size=(m, 8))
    return np.vstack([N, A]), np.r_[np.zeros(n0), np.ones(m)].astype(bool)

def detectores(X, seed):
    """Ocho puntuaciones (mayor = más anómalo) con hiperparámetros por defecto, sin tunear, sobre datos estandarizados."""
    Z = StandardScaler().fit_transform(X)
    n, d = Z.shape
    out = {}
    out["Mahalanobis"] = EmpiricalCovariance().fit(Z).mahalanobis(Z)
    out["MCD"] = MinCovDet(random_state=seed).fit(Z).mahalanobis(Z)
    out["GMM"] = -GaussianMixture(3, reg_covar=1e-3, random_state=seed).fit(Z).score_samples(Z)
    out["KDE"] = -KernelDensity(bandwidth=n ** (-1 / (d + 4))).fit(Z).score_samples(Z)      # regla de Scott
    out["k-NN"] = NearestNeighbors(n_neighbors=11).fit(Z).kneighbors(Z)[0][:, 10]
    out["LOF"] = -LocalOutlierFactor(n_neighbors=20).fit(Z).negative_outlier_factor_
    out["IForest"] = -IsolationForest(n_estimators=100, random_state=seed).fit(Z).score_samples(Z)
    out["OCSVM"] = -OneClassSVM(gamma="scale", nu=0.05).fit(Z).decision_function(Z)
    return out

def evalua(X, y, seed):
    k = int(y.sum())
    r = {}
    for nombre, s in detectores(X, seed).items():
        top = np.argsort(-s)[:k]
        r[nombre] = (average_precision_score(y, s), y[top].mean())      # PR-AUC y precisión en k
    return r

resultados = {}                     # (conjunto, repetición) -> {detector: (PR-AUC, precisión en k)}
t0 = time.time()
for nombre in ("globales", "locales"):
    for rep in range(3):
        X, y = escenario(nombre, np.random.default_rng(100 + rep))
        resultados[(nombre, rep)] = evalua(X, y, rep)
print(f"{len(resultados)} conjuntos evaluados en {time.time() - t0:.1f} s")
[ ]Benchmark: clustered anomaliesBrowser
t0 = time.time()
for rep in range(3):
    X, y = escenario("agrupadas", np.random.default_rng(100 + rep))
    resultados[("agrupadas", rep)] = evalua(X, y, rep)
print(f"{len(resultados)} conjuntos evaluados en {time.time() - t0:.1f} s")
[ ]Benchmark: subspaceBrowser
t0 = time.time()
for rep in range(3):
    X, y = escenario("subespacio", np.random.default_rng(100 + rep))
    resultados[("subespacio", rep)] = evalua(X, y, rep)
print(f"{len(resultados)} conjuntos evaluados en {time.time() - t0:.1f} s")
[ ]Benchmark: digits with one anomalous classBrowser
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA

dig = load_digits()
t0 = time.time()
for clase in (0, 4, 7):                         # cada clase hace de anomalía una vez (5 %); el resto son las normales
    for rep in range(2):
        rng = np.random.default_rng(200 + 10 * clase + rep)
        i_a = rng.choice(np.where(dig.target == clase)[0], 15, replace=False)
        i_n = rng.choice(np.where(dig.target != clase)[0], 285, replace=False)
        X = PCA(10, random_state=0).fit_transform(dig.data[np.r_[i_n, i_a]])        # sin etiquetas
        y = np.r_[np.zeros(285), np.ones(15)].astype(bool)
        resultados[(f"dígito {clase}", rep)] = evalua(X, y, rep)
print(f"{len(resultados)} conjuntos evaluados en {time.time() - t0:.1f} s")
[ ]Benchmark: results and statistical comparisonBrowser
import pandas as pd
from scipy import stats

nombres = list(next(iter(resultados.values())).keys())
conjuntos = sorted({c for c, _ in resultados})
def media(i):
    return pd.DataFrame({d: {c: np.mean([resultados[(c, r)][d][i] for (cc, r) in resultados if cc == c]) for c in conjuntos} for d in nombres})
print("PR-AUC media:")
print(media(0).round(2).to_string())
print("\nprecisión en k (k = número de anomalías, 15 de 300):")
print(media(1).round(2).to_string())

# un bloque por (conjunto, repetición): 18 bloques, 8 detectores; rangos de PR-AUC (1 = el mejor)
AP = np.array([[resultados[b][d][0] for d in nombres] for b in resultados])
rangos = np.apply_along_axis(lambda f: stats.rankdata(-f), 1, AP)
print("\nrango medio de PR-AUC (menor es mejor):", {d: round(float(r), 2) for d, r in zip(nombres, rangos.mean(0))})
chi, p = stats.friedmanchisquare(*AP.T)
print(f"Friedman: chi2 = {chi:.1f}, p = {p:.2g} sobre {len(AP)} bloques")
mejor = nombres[int(np.argmin(rangos.mean(0)))]
for d in nombres:
    if d != mejor:
        w = stats.wilcoxon(AP[:, nombres.index(mejor)], AP[:, nombres.index(d)])
        print(f"  {mejor} frente a {d:12s}: diferencia media de PR-AUC {np.mean(AP[:, nombres.index(mejor)] - AP[:, nombres.index(d)]):+.3f}, Wilcoxon p = {w.pvalue:.3f}")
[ ]Benchmark: sensitivity to contaminationBrowser
# el mismo detector sobre datos con 2 %, 10 % y 20 % de anomalías
t0 = time.time()
sens = {}
for contam in (0.02, 0.10, 0.20):
    for nombre in ("globales", "agrupadas"):
        X, y = escenario(nombre, np.random.default_rng(300), contam=contam)
        sens[(contam, nombre)] = evalua(X, y, 0)
print(f"{time.time() - t0:.1f} s")
for nombre in ("globales", "agrupadas"):
    print(f"\nPR-AUC en '{nombre}':")
    print(pd.DataFrame({c: {d: v[0] for d, v in sens[(c, nombre)].items()} for c in (0.02, 0.10, 0.20)}).round(2).T.to_string())

The first table gives each detector’s mean PR-AUC on each dataset; the second precision at kk with k=15k = 15, the number of anomalies: of 15 alerts an analyst reviews, how many are real? First, each scenario has a different winner:

  • For global anomalies, seven of eight detectors score 0.80 to 0.88 (GMM and Isolation Forest 0.88); One-Class SVM with ν=0.05\nu = 0.05 and default γ\gamma scores 0.67.
  • For local anomalies, only LOF (0.84) and, at a distance, GMM (0.50) see anomalies near the dense group; Mahalanobis (0.06), MCD (0.05), KDE (0.08) and tenth-neighbor distance (0.12) barely beat chance (prevalence 0.05).
  • For clustered anomalies, only MCD (0.94) sees the 15-point microcluster well, and classical Mahalanobis partly (0.62); the other six score 0.03 to 0.24: for neighbor and density methods the microcluster is a normal neighborhood, and tenth-neighbor distance with k=10k = 10 smaller than the microcluster is worst (0.03).
  • In subspace, Mahalanobis and MCD reach 1.00; LOF 0.86; KDE and GMM about 0.80; neighbor distance 0.61; One-Class SVM 0.49; and Isolation Forest 0.27, lowest: per-feature cuts do not see broken correlation.
  • On digits, none exceeds 0.45: a digit class is not a geometric anomaly (a 7 is as dense a cloud as the others) and these detectors see little. MCD is best for two of three classes (0.33 with class 0, 0.45 with 7) and LOF for class 4 (0.20), but differences are small.

Precision at kk tells the same story in the analyst’s language, more starkly. For local anomalies, LOF gives 0.87 (about 13 of 15 real alerts) and Mahalanobis and MCD 0.00: all their 15 alerts are normal. For clustered anomalies, MCD gives 0.93 and KDE, LOF and neighbor distance 0.00. A PR-AUC of 0.14 (LOF on clustered) sounds like it sees something; precision at kk of 0 says the analyst would receive no anomaly on the list.

With 18 blocks (dataset and repeat), the Friedman test rejects equivalence of the eight detectors (χ2=30.4\chi^2 = 30.4, p=7.9⋅10−5p = 7.9\cdot10^{-5}). Mean ranks (lower is better) are 3.25 (Mahalanobis), 3.39 (LOF), 3.42 (MCD), 4.0 (GMM), 4.5 (Isolation Forest), 5.44 (KDE), 5.5 (tenth-neighbor distance), and 6.5 (One-Class SVM). But the first four are not distinguished: against Mahalanobis, Wilcoxon gives p=0.121p = 0.121 for MCD, 0.468 for LOF, and 0.227 for GMM, and even Isolation Forest is unclear (0.090); only KDE (0.002), neighbor distance (0.016) and One-Class SVM (0.001) are clearly behind (without multiple-comparison correction, and blocks are not independent because each dataset is repeated). Also “best” depends on the summary: Mahalanobis has best mean rank, but MCD’s mean PR-AUC is 0.093 higher, because when it wins (clustered, digits 0 and 7) it wins by much. Read cautiously: order depends on the scenario mix (three here have Gaussian group structure, favoring ellipses); it is not a universal ranking.

Much larger studies find the same. ADBench (Han and coauthors, 2022) compares 30 algorithms on 57 datasets and concludes none of the unsupervised ones is statistically better than the others, and performance depends mainly on detector assumptions matching anomaly type: for its synthetic anomalies, LOF is best on local ones and kk-neighbor distance on global and dependency anomalies. On clustered anomalies its best unsupervised method is One-Class SVM, not MCD as here: what transfers between benchmarks is dependence on anomaly type and hyperparameters, not a specific ranking.

The last table changes contamination (with the same detectors). Be careful comparing PR-AUC across rows: a random-scoring detector’s PR-AUC is prevalence, so it rises with contamination for that reason alone. What matters is relative movement:

  • For global anomalies almost all improve as contamination rises (Mahalanobis, 0.78 to 0.91): more anomalies raise baseline PR-AUC. One-Class SVM is the exception: 0.79 to 0.38, because fixed ν=0.05\nu = 0.05 lets the boundary exclude at most 5% of points and with 20% anomalies must enclose many with normals.
  • For clustered anomalies, MCD stays between 0.86 and 0.99 even with 20% anomalies (less than the 50% it tolerates), while GMM falls from 0.30 to 0.06 and 0.11 (with three components one can fit the microcluster, as in the zoo), and tenth-neighbor distance from 0.50 to 0.05: as contamination grows, the microcluster exceeds kk and ceases to be rare to its own neighbors.

Practical detector selection: first define what anomaly type matters (global, local, collective, in the correlation subspace), test two or three detectors from different families on a labeled sample, however small, and inspect PR-AUC and precision at kk under different contamination levels. If important anomalies have several types, consider combining scores from different families by rank (for example, average LOF and MCD ranks): a point highly ranked by either rises in the combination, at the price of inheriting some false alarms from both. Validate it using the same metrics before relying on it.

Common mistakes

Exercises

ProofA threshold with controlled false-positive rate
Prove: Let X∼N(μ,Σ)X \sim \Normal(\vb{\mu}, \mat{\Sigma}) in Rp\R^p with positive definite Σ\mat{\Sigma}. Then d2(X)=(X−μ)⊤Σ−1(X−μ)∼χp2d^2(X) = (X - \vb{\mu})\T\mat{\Sigma}\inv(X - \vb{\mu}) \sim \chi^2_p, and the detector 'alert if d2>χp,1−α2d^2 > \chi^2_{p,1-\alpha}' has false-positive rate α\alpha on normal data.
0
Assume μ\vb{\mu} and Σ\mat{\Sigma} are known. Recall that χp2\chi^2_p is the distribution of the sum of squares of pp independent standard normals.

Step 1 of 4. What transformation takes XX to a standard vector?

NumericIsolation Forest score
An Isolation Forest uses subsamples of ψ=256\psi = 256 points, for which c(256)≈10.25c(256) \approx 10.25. A point has mean tree path length E[h(x)]=5\E[h(\vb{x})] = 5. What is its score s=2−E[h]/c(ψ)s = 2^{-\E[h]/c(\psi)}?
QuizAn outlier near a dense group
There is a compact group whose points are tenths of units apart, and a sparse one whose points are units apart. A point is near the compact group (about 6 times its spread) but that distance is below sparse-group neighbor distances. Why does LOF detect it while kkth-neighbor distance does not?
CodeLOF from scratch, including new points
Implement lof_scores(X, k, X_new=None), without sklearn.neighbors, using Euclidean distance and lrdk(a)=1/(rˉa+10−10)\mathrm{lrd}_k(a) = 1/(\bar{r}_a + 10^{-10}), where rˉa\bar{r}_a is mean reachability distance to kk neighbors. Without X_new, return LOF for each row of X (a point is not its own neighbor), as in the lab. With X_new, return LOF for each row of X_new relative to X, as needed in production to score data arriving after training: determine which neighbors, kdist⁡\operatorname{kdist} and lrd\mathrm{lrd} are involved. Tests compare with scikit-learn LocalOutlierFactor, with and without novelty=True.
import numpy as np

def lof_scores(X, k, X_new=None):
  """LOF_k de las filas de X (X_new = None) o de las filas de X_new respecto de X."""
  m = len(X) if X_new is None else len(X_new)
  # tu código: kdist y lrd de los puntos de X; después, el caso X_new
  return np.ones(m)
Shift+Enter to run
Quiz99% and 99% at prevalence 1 in 10,000
A detector has 99% sensitivity and 99% specificity and is applied to a stream with anomaly prevalence 1 in 10,000. Approximately what fraction of alerts are real? If a redesign raised sensitivity to 100% without changing specificity, what fraction would be real?
NumericRequired false-positive rate
With prevalence π=10−4\pi = 10^{-4} and sensitivity 99%, what maximum false-positive rate makes half the alerts real (50% precision)?
QuizMasking and swamping
You train classical Mahalanobis with 20% clustered outliers. Which description is correct?
QuizWhat ν guarantees
You train One-Class SVM with ν=0.05\nu = 0.05 and n=1000n = 1000 points. What is guaranteed for any solution?
QuizChoosing a detector by structure
You monitor 40 correlated sensors in an industrial process. A fault breaks the relation between several without taking any out of its usual range. You have weeks of data with some unlabeled faults. What is your first choice?
QuizROC, PR and alert budget
Which statements about evaluating detectors at very low prevalence are true?

More than one answer may be correct.

QuizA point on the line but far away
With rank-1 PCA on data nearly on a line, a point lies exactly on the line but 8 standard deviations from the center along it. What do T2T^2, QQ and d2d^2 say?

Summary

Key idea
Every unsupervised anomaly detector is a score plus a threshold. Scores come from four ideas: low density (KDE, GMM, Mahalanobis, neighbor distance and LOF), easy isolation (Isolation Forest), outside the region containing nearly everything (One-Class SVM), and poor reconstruction (PCA and autoencoders). None wins in every case: each has a blind spot, and with low prevalence the decisive metric is precision, not ROC.
  • Framing. Score ss and threshold τ\tau; the threshold is an operational decision and contamination estimates nothing. Anomalies may be point, contextual or collective, and training can be clean (novelty) or contaminated (outliers). Against uniform anomalies the optimal score is normal density (Neyman–Pearson).
  • Mahalanobis and MCD. Under normality with known parameters, d2∼χp2d^2 \sim \chi^2_p and threshold χp,1−α2\chi^2_{p,1-\alpha} gives exact FPR; with estimated parameters and small nn it is optimistic. Classical mean and covariance suffer masking and swamping; MCD, with determinant-nonincreasing C-steps, resists contamination below 1−h/n1 - h/n.
  • LOF. Each point’s density relative to its neighbors using reachability distances; equals 1 in homogeneous regions and is scale invariant. Distinguishes sparse from rare when densities differ; to see a microcluster as anomalous, kk must be substantially larger than group size.
  • Isolation Forest. Random-cut path length normalized by c(ψ)c(\psi) (cc is exact for binary search trees and approximate for nonuniform data); small subsamples combat masking; axis-parallel cuts miss correlations.
  • One-Class SVM and reconstruction. ν\nu upper-bounds the training fraction outside the boundary and lower-bounds support-vector fraction. d2=T2+d^2 = T^2 + weighted residual and QQ = unweighted residual: QQ misses extremes within the subspace and classical PCA learns anomalies in contaminated training.
  • Evaluation. ROC does not depend on prevalence but precision does (Bayes): with 99% and 99% and π=10−4\pi = 10^{-4}, only 1 in 100 alerts is real. Use PR-AUC, precision at kk, and false alerts per real alert, and declare prevalence.