Monday, 30 November 2026

Autoencoders and PCA reconstruction error (Part 5)

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

The summary first:

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

The idea

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

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

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

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

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

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

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

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

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

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

Checking the formula against scikit-learn

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

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

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

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

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

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

Dataset A: 10 features, 3 hidden factors

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

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

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

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

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

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

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

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

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

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

import matplotlib.pyplot as plt

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

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

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

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

Ranking comparison on dataset A

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

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

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

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

What the table says:

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

Choosing the number of components

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

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

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

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

Dataset B: when the structure is curved

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

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

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

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

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

from sklearn.neural_network import MLPRegressor

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

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

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

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

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

The result depends on the training details

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

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

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

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

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

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

Comparison with the earlier methods on dataset B

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

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

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

Novelty detection

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

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

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

Practical notes

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

Conclusion

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

References:

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

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

Autoencoders and PCA reconstruction error (Part 5)

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