Autoencoders: Linear, Nonlinear and PCA
An autoencoder is a model trained to copy its input to its output through a narrow middle layer, the code or bottleneck. Because the code is smaller than the input, the model cannot simply copy; it has to learn a compressed description that keeps what matters for rebuilding the input. It is the neural-network version of PCA, and in its simplest form it is exactly PCA. This lesson shows that equivalence in NumPy, then trains a small nonlinear autoencoder in PyTorch and uses its reconstruction error to detect anomalies. Neural networks themselves are the subject of the Deep Learning course of this track; here only the idea is needed.
Architecture and loss
An encoder maps the input to a code with , a decoder maps it back, and both are trained together to minimise the reconstruction error
No labels are needed: the input is its own target, which makes autoencoders a form of self-supervised learning.
The linear autoencoder is PCA
Take and , with no nonlinearity and centred data. The reconstruction is then a matrix of rank at most , and the best rank- approximation of a matrix in squared error is given by its top singular vectors (the Eckart-Young theorem, Matrix Approximation, Low-Rank Approximation). So the optimal linear autoencoder reconstructs exactly as well as PCA with components, and its decoder spans the same subspace. It need not find the components themselves: any invertible mixing of them inside the code works equally well.
Gradient descent on the digits (64 pixels, centred, code size 8), compared with PCA:
import numpy as np
from scipy.linalg import subspace_angles
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
X, _ = load_digits(return_X_y=True)
X = (X - X.mean(axis=0)) / 16 # centre; pixels scaled to about [-1, 1]
n, d, k = X.shape[0], X.shape[1], 8
rng = np.random.default_rng(0)
W_enc = rng.normal(scale=0.1, size=(d, k)) # encoder: 64 -> 8
W_dec = rng.normal(scale=0.1, size=(k, d)) # decoder: 8 -> 64
lr = 0.5
for step in range(3001):
Z = X @ W_enc # codes
R = Z @ W_dec - X # reconstruction error
loss = (R ** 2).sum() / n
if step in (0, 100, 1000, 3000):
print(f"step {step:4d} reconstruction MSE per image {loss:.4f}")
G = 2 * R / n # dLoss/dReconstruction
grad_dec = Z.T @ G
grad_enc = X.T @ (G @ W_dec.T)
W_dec -= lr * grad_dec
W_enc -= lr * grad_enc
pca = PCA(n_components=k).fit(X)
pca_loss = ((pca.inverse_transform(pca.transform(X)) - X) ** 2).sum() / n
print("PCA with 8 components: reconstruction MSE per image", round(pca_loss, 4))
angles = np.degrees(subspace_angles(W_dec.T, pca.components_.T))
print("largest angle between the autoencoder's subspace and PCA's:", round(angles.max(), 2), "degrees")step 0 reconstruction MSE per image 4.9822
step 100 reconstruction MSE per image 1.5350
step 1000 reconstruction MSE per image 1.5305
step 3000 reconstruction MSE per image 1.5305
PCA with 8 components: reconstruction MSE per image 1.5304
largest angle between the autoencoder's subspace and PCA's: 0.01 degrees
After training, the linear autoencoder's error (1.5305 per image) is PCA's (1.5304) up to the last digit, and the 8-dimensional subspace spanned by its decoder lies within 0.01 degrees of the space of the first 8 principal components. The two gradients are the chain rule applied to (Backpropagation and Automatic Differentiation).
A nonlinear autoencoder (recorded, PyTorch)
With nonlinear activations between layers, an autoencoder can follow curved structure that PCA cannot. This example is recorded (PyTorch does not run in the browser): a 64-32-8-32-64 network with ReLU layers trained only on digits 0 to 4, then used to score unseen digits 0 to 4 and digits 5 to 9. A digit unlike anything in training should be rebuilt badly, so its reconstruction error works as an anomaly score:
import numpy as np
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.metrics import roc_auc_score
torch.manual_seed(0)
X, y = load_digits(return_X_y=True)
X = (X / 16).astype(np.float32)
normal = y <= 4 # train only on digits 0-4
rng = np.random.default_rng(0)
idx = rng.permutation(np.flatnonzero(normal))
train, test_normal = idx[:700], idx[700:]
test = np.r_[test_normal, np.flatnonzero(~normal)[:200]] # unseen normals + 200 digits 5-9 as anomalies
is_anomaly = np.r_[np.zeros(len(test_normal)), np.ones(200)]
model = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 8), nn.ReLU(),
nn.Linear(8, 32), nn.ReLU(), nn.Linear(32, 64), nn.Sigmoid())
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
Xt = torch.from_numpy(X[train])
for epoch in range(300):
opt.zero_grad()
loss = ((model(Xt) - Xt) ** 2).mean()
loss.backward()
opt.step()
if epoch + 1 in (1, 100, 300):
print(f"epoch {epoch + 1:3d} training MSE {loss.item():.4f}")
with torch.no_grad():
err_ae = ((model(torch.from_numpy(X[test])) - torch.from_numpy(X[test])) ** 2).mean(dim=1).numpy()
pca = PCA(n_components=8).fit(X[train])
err_pca = ((pca.inverse_transform(pca.transform(X[test])) - X[test]) ** 2).mean(axis=1)
print("mean error on unseen 0-4: autoencoder", round(err_ae[is_anomaly == 0].mean(), 4), " PCA", round(err_pca[is_anomaly == 0].mean(), 4))
print("ROC AUC for flagging 5-9 by reconstruction error: autoencoder", round(roc_auc_score(is_anomaly, err_ae), 3),
" PCA", round(roc_auc_score(is_anomaly, err_pca), 3))epoch 1 training MSE 0.1848
epoch 100 training MSE 0.0468
epoch 300 training MSE 0.0281
mean error on unseen 0-4: autoencoder 0.0299 PCA 0.0199
ROC AUC for flagging 5-9 by reconstruction error: autoencoder 0.945 PCA 0.908
Two results that pull in different directions, both worth knowing. On unseen digits of the trained kinds, PCA with 8 components reconstructs better than this small, briefly trained network (0.0199 against 0.0299): with 700 training images, a nonlinear model does not automatically beat the linear optimum. As an anomaly detector, the autoencoder is better (ROC AUC 0.945 against 0.908): its reconstructions are specialised to the shapes of 0 to 4, so a 7 or an 8 comes out worse than under PCA, which rebuilds any image that is close to its linear subspace.
Variants
| Variant | Idea | Use |
|---|---|---|
| undercomplete | a code smaller than the input (above) | compression, features, anomaly scores |
| denoising | corrupt the input, reconstruct the clean version | robust features, denoising |
| sparse | a penalty keeps most code units at zero | interpretable features |
| variational (VAE) | the code is a distribution; sampling generates new data | generative modelling |
Strengths, weaknesses, when to use it
Autoencoders learn nonlinear compressions from unlabelled data, work for images, audio, sequences and tabular data alike, and their reconstruction error is a general-purpose anomaly score. They need more data, tuning and compute than PCA, their codes are hard to interpret, and a too-powerful autoencoder can learn to reconstruct anomalies too. Start with PCA; move to an autoencoder when the data is clearly nonlinear (images, signals) and you have enough of it.
Pitfalls
- Judging by training reconstruction only. Like any model, an autoencoder can overfit; compare on held-out data.
- A bottleneck that is too wide. With a code as large as the input, the network can learn the identity and nothing useful.
- Anomaly thresholds from the training error. Training errors are optimistically low; set the threshold on validation data.
Practice
- A linear autoencoder with code size 8 on centred data reaches the same error as PCA with 8 components, but its encoder weights differ from the principal components. Is something wrong?
Answer
No. Any invertible matrix can be absorbed: and give the same reconstruction. Only the subspace spanned by the decoder is determined, and it equals the span of the top 8 components, which is what the angle check confirmed.
- Why might an autoencoder trained on normal transactions fail to flag a new type of fraud that looks like a mix of normal transactions?
Answer
It flags inputs it cannot reconstruct. A fraud pattern made of familiar parts can be reconstructed well, so its error stays low. Reconstruction error detects the unfamiliar, not the harmful.
Test yourself
What is an autoencoder trained to output?
- The class label
- Its own input, through a smaller code
- Random noise
- The principal components
What does a linear autoencoder with squared error learn, at its optimum?
- Nothing useful
- The same subspace as PCA with the same number of components
- A k-means clustering
- A nonlinear manifold
How can an autoencoder detect anomalies without labels?
- By classifying them
- Points unlike the training data are reconstructed badly, so a high reconstruction error flags them
- By clustering the codes
- By counting parameters