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
- 12Kernel density estimationk-nearest-neighbor density estimationGaussian mixture modelPCA as minimum reconstruction errorRobust PCA (principal component pursuit)DBSCAN
- 11Decision tree (CART)SVM dual problemKernel support vector machineROC curve and AUCPrecision-recall curve
- 04Exponential, gamma and chi-squared distributionsBayes' theorem
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 saying how much 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 with kernel density accounts for local shape. All are evaluated using the same labels (used only for measurement, never fitting).
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 , 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 . 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 to the training-score quantile leaving that fraction above it. Choosing 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- test rejects when likelihood ratio exceeds a constant , accepts when it is lower, and randomizes on equality if needed. On , (equal to where ), a strictly decreasing function of ; outside , and that set has probability zero under both hypotheses. Thus is equivalent to , and to .
∎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 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 when 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 but rank points similarly.
Density scores: Gaussian, mixture and kernels
If you estimate , the score is . Three familiar families:
- A Gaussian : the score is, up to constants, Mahalanobis distance, discussed next.
- A Gaussian mixture fitted by EM: models several groups at the cost of choosing .
- A kernel density estimate : nonparametric, with bandwidth 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, , so no training point can score above : 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 component capturing the microcluster and treating it as normal.
A third problem is dimension: small-radius neighborhoods empty out and 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 is from the center in the covariance metric: . Its great virtue is exact calibration under normality.
Proof
Since with diagonal of positive entries, symmetric root exists. Let : it is a linear transform of a Gaussian vector, hence Gaussian, with mean and covariance . Components are therefore independent and by definition. The probability that is , equal to exactly when .
∎This connects to the gamma family: a is a (exponential and gamma family). But the theorem assumes known parameters. In practice you estimate and from the same data, and the result is only approximate, worsening as becomes small relative to :
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, (the cell gives 4.985) and false-positive rate is 0.0100, the nominal rate. With parameters estimated from points, the actual rate is 0.0531, five times nominal; with , 0.0187; with , 0.0107. The threshold is optimistic with few data: do not use it as a guarantee without checking .
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 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.
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 . With at most outliers there is a subset of points excluding them all, so tolerated contamination is of order : for data in general position, its breakdown point (smallest fraction of points that can move the estimate arbitrarily when moved at will) is , maximal and near 50% with (Rousseeuw and Van Driessen, 1999). The price of robustness: small uses fewer data and loses estimator efficiency, while the exact solution is combinatorial ( subsets).
Rousseeuw and Van Driessen’s FastMCD relies on an elegant result: a step improving any subset.
Proof
Sum the quadratic form over using that a scalar equals its trace and trace is cyclic: . Since collects the smallest values, .
Let , the scatter of around . It decomposes as , and . Eigenvalues of sum to at most , and by the arithmetic–geometric mean inequality,
Since , .
∎Repeating C-steps from any start yields a nonincreasing determinant sequence that stops at a local minimum. FastMCD launches many random starts (with 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 . Implement it from scratch in the next cell and check against scikit-learn:
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 and detects none (0 of 25; flags 2 normal points), whereas MCD with estimates mean 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 and substantially greater than 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 th neighbor . This is in fact the -neighbor density estimate score: with the unit-ball volume, and thus , an increasing function of . Detecting with th-neighbor distance is detecting with -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.
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 is in a region as dense as its neighbors’, their lrd values are equal and ; if is much less dense than its neighbors, . Reachability distance (with ) smooths fluctuations: two points very close to the same neighbor are treated as if at its , 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 multiplies all distances and thus all by , divides by , and leaves ratios unchanged. The cell confirms this (maximum difference on multiplying by 10 is , due to the constant scikit-learn adds for stability). Distance to the th neighbor, by contrast, is multiplied by : 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 : compute LOF over a range and take the maximum, so neither small (which sees noise) nor above group size hides the anomaly. The 6-point microcluster in the zoo below illustrates this: with its points see only one another, are as dense as their neighbors, and their LOF is near 1. Nor is it enough for to exceed group size: at , half the neighbors are still groupmates and LOF flags none of the 6 (at the 8% threshold); at it flags 1, and at all 6. Therefore Breunig and coauthors set the upper bound of the 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 neighbors within distance , are outliers. It is a binary score with global (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 ? A complete isolation tree has the structure of a decision tree with one point per leaf: leaves and internal nodes. It has the form of a binary search tree with keys inserted in random order, whose leaves (gaps between keys) have average depth , with the th harmonic number: the mean length of an unsuccessful search. Since and , we obtain the formula for (for the harmonic approximation is poor, so the exact value is used). This is the typical path length of a point in a set of points; dividing by it gives a score comparable across subsample sizes. Thus:
- gives : the point isolates as fast as a typical one.
- gives : it isolates immediately and is highly anomalous.
- Large gives : very normal.
If all points have , there are no clear anomalies.
A rarely stated caveat: 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:
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 ) reproduces ; 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 is a reasonable normalization, not an exact expectation, and should be read as an ordinal scale with 0.5 an approximate reference: with bell-shaped data a typical point has somewhat below 0.5.
Why small subsamples. With (the original proposal’s default and scikit-learn’s max_samples='auto', using ), the forest does not see all data in each tree. This reduces cost (each tree is small: training costs , independent of , and scoring a point ) 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 the forest flags all 6 microcluster points; with , only 3.
See how a path is built and what happens to the score.
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:
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 has (the 99.9% threshold of a is 13.8), but the forest gives it , almost the same as , a normal diagonal point (, ), 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.
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 . 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 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 cell showed, with bell-shaped data actual mean path length exceeds . 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 . 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 of points on the other side.
The most useful part of the dual is what optimality (KKT) conditions say: implies (inside); implies (on the boundary or outside) and ; and implies (on the boundary). The property giving the parameter meaning follows.
Proof
(a) If , constraint forces , and complementary slackness and the bound condition (the multiplier of is ) give . Since , at most indices can equal . (b) Each is at most and they sum to 1, so at least indices with are needed.
∎With the RBF kernel, for every 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 , , so being on the good side of the hyperplane, , is equivalent to being inside the ball centered at with squared radius . That is why the detector estimates a level set, not a density: its boundary depends on support vectors, the most extreme points, and on (kernel width, ), setting the scale. Check the property with scikit-learn:
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 is at most and the support-vector fraction at least as large (with : 0.082 and 0.114). scikit-learn normalizes the dual with and , the same problem multiplied by : the sum is exactly 50 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, bounds the training fraction outside the boundary, not the future false-alarm rate, although for large and under kernel and distribution conditions the fractions converge to (Schölkopf and coauthors, 2001). Second, the method is not scale invariant: uses data units. The zoo figure shows that large makes the boundary hug each point, while small 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 -dimensional subspace minimizing mean squared reconstruction error.
What does see that Mahalanobis does not, and vice versa? There is an exact decomposition. With the principal-component coordinates:
The first equality is the definition of in the eigenbasis; the second follows because projection onto the orthogonal complement has coordinates with and the basis is orthonormal. Two immediate readings:
- (Hotelling’s subspace ) detects anomalies inside the subspace: points far along principal directions that does not see because residual is small.
- weights residual uniformly and weights it by . With very small (directions with almost no variance), Mahalanobis greatly amplifies any deviation; does not. If data have substantial isotropic noise in those directions, Mahalanobis dilutes the signal among many noise components, whereas with well-chosen sums only the residual.
If is Gaussian and mean and covariance are the true ones, and the residual part of is , independent of it; by contrast, is a weighted combination of variables, not a , so its threshold is approximated (Jackson and Mudholkar, 1979, give a classic approximation) or calibrated empirically. The next figure uses the one-dimensional threshold , exact for .
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.
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), obtains PR-AUC 0.83 and Mahalanobis 0.71, while obtains 0.04: it cannot see them because their residual is normal. For type B (outside the subspace), and Mahalanobis reach 1.00 and stays at 0.03. Notice Mahalanobis (0.71) performs worse than on type A: it adds seven noise terms to , 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 ( 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 with low-rank and sparse , and 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.
Read this as a risk map, not a ranking. No detector wins on every front: LOF with small sees local but not collective anomalies; distance to the 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 and with consistently scaled data; density scores need one bandwidth or a reasonable . 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 (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 yields precision : one alert in a hundred is real. The cell simulates such a binormal detector ( scores for normals and for anomalies, with ) on 500,000 points:
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 to 0.497, 0.0895 and 0.0098 at , 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 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.
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 ) 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 , 100-tree Isolation Forest, and One-Class SVM with scale and . 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 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.
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")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")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")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")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}")# 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 with , 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 and default 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 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 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 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 (, ). 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 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 -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 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 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 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
Step 1 of 4. What transformation takes to a standard vector?
lof_scores(X, k, X_new=None), without sklearn.neighbors, using Euclidean distance and , where is mean reachability distance to 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, and 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)More than one answer may be correct.
Summary
- Framing. Score and threshold ; the threshold is an operational decision and
contaminationestimates 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, and threshold gives exact FPR; with estimated parameters and small it is optimistic. Classical mean and covariance suffer masking and swamping; MCD, with determinant-nonincreasing C-steps, resists contamination below .
- 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, must be substantially larger than group size.
- Isolation Forest. Random-cut path length normalized by ( 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. upper-bounds the training fraction outside the boundary and lower-bounds support-vector fraction. weighted residual and = unweighted residual: 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 , only 1 in 100 alerts is real. Use PR-AUC, precision at , and false alerts per real alert, and declare prevalence.