Autoencoders: Undercomplete, Denoising and Sparse
The Generative Models section starts with a model that does not generate anything yet. An autoencoder learns to rebuild its input through a narrow code, and that simple task turns out to be useful for compression, denoising, anomaly detection and feature learning. Autoencoders: Linear, Nonlinear and PCA showed that a linear autoencoder learns the same subspace as PCA, and the masked and denoising pretext tasks of Self-Supervised Pretraining are the same idea used for pretraining. This lesson builds on both. You write the backward pass of a nonlinear autoencoder yourself, train denoising and sparse variants, check how good the codes are as features, measure anomaly detection one digit class at a time, and see why sampling from a plain autoencoder's code space works badly. That last point is what Variational Autoencoders fix.
All numbers come from the course's Digits split: 1077 training, 360 validation and 360 test images of pixels scaled to . Every choice here is made on validation data. The test set is not used, because this lesson compares methods and does not report a final model.
Three ways to stop the network from copying
An autoencoder is an encoder and a decoder trained together so that is close to . If the network can learn the identity function, it will, and the code then tells you nothing new about the data. Each variant stops that in a different way:
| Variant | What stops the identity | Loss for one image |
|---|---|---|
| undercomplete | a code smaller than the input, | |
| denoising | the input is corrupted, the target is clean | |
| sparse | only a few code units may be active |
The corruption used below is masking noise: each pixel is set to 0 with probability . A denoising autoencoder has to fill in the missing strokes, which it can only do if it has learned what digits look like. With small Gaussian corruption, the optimal denoiser can be shown to point from a corrupted point back towards the data along the gradient of the log density, the score (Vincent, 2011). That fact comes back in diffusion models. The L1 penalty is the same one as in lasso regression. Its subgradient pushes every code unit towards zero at a constant rate, so only the units that pay for themselves stay on (Regularization).
A nonlinear autoencoder in NumPy
The network below is 64-32-8-32-64 with ReLU hidden layers, a linear 8-unit code and a sigmoid output, trained with mean squared error and Adam. The backward pass is the layer-by-layer chain rule from Backpropagation, Layer by Layer. It goes through a list of layers in reverse and multiplies by each activation's derivative. After training, the 8-number codes are tested as features for a logistic regression. The last lines draw random codes and decode them.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
rng = np.random.default_rng(0)
sizes = [64, 32, 8, 32, 64] # encoder 64-32-8, decoder 8-32-64
P = []
for a, b in zip(sizes[:-1], sizes[1:]):
P += [rng.normal(0, np.sqrt(2 / a), (a, b)), np.zeros(b)]
acts = ["relu", "none", "relu", "sigmoid"] # code layer is linear
def forward(x):
hs = [x]
for i, act in enumerate(acts):
z = hs[-1] @ P[2 * i] + P[2 * i + 1]
hs.append(np.maximum(z, 0) if act == "relu" else 1 / (1 + np.exp(-z)) if act == "sigmoid" else z)
return hs # hs[2] is the code, hs[4] the reconstruction
def backward(hs, x):
g = 2 * (hs[-1] - x) / x.size # d(MSE)/d(output)
grads = [None] * len(P)
for i in reversed(range(len(acts))):
h = hs[i + 1]
if acts[i] == "relu": g = g * (h > 0)
elif acts[i] == "sigmoid": g = g * h * (1 - h)
grads[2 * i], grads[2 * i + 1] = hs[i].T @ g, g.sum(axis=0)
g = g @ P[2 * i].T
return grads
m = [np.zeros_like(p) for p in P]; v = [np.zeros_like(p) for p in P]
lr, t = 3e-3, 0
for epoch in range(1, 101):
for idx in np.array_split(rng.permutation(len(X_tr)), 17): # batches of about 64
xb = X_tr[idx]
grads = backward(forward(xb), xb)
t += 1
for k, g in enumerate(grads): # Adam
m[k] = 0.9 * m[k] + 0.1 * g; v[k] = 0.999 * v[k] + 0.001 * g * g
P[k] -= lr * (m[k] / (1 - 0.9 ** t)) / (np.sqrt(v[k] / (1 - 0.999 ** t)) + 1e-8)
if epoch in (1, 10, 100):
mse = np.mean((forward(X_va)[-1] - X_va) ** 2)
print(f"epoch {epoch:3d} validation MSE {mse:.4f}")
pca = PCA(n_components=8).fit(X_tr)
print(f"PCA, 8 components: validation MSE {np.mean((pca.inverse_transform(pca.transform(X_va)) - X_va) ** 2):.4f}")
Z_tr, Z_va = forward(X_tr)[2], forward(X_va)[2]
for name, a, b in [("raw 64 pixels", X_tr, X_va), ("PCA 8 codes", pca.transform(X_tr), pca.transform(X_va)),
("AE 8 codes", Z_tr, Z_va)]:
clf = LogisticRegression(max_iter=2000).fit(a, y_tr)
print(f"logistic regression on {name:13s}: validation accuracy {clf.score(b, y_va):.3f}")
# Is the code space a good place to sample from? Draw codes with the same per-unit mean and spread
clf = LogisticRegression(max_iter=2000).fit(X_tr, y_tr) # judge: a pixel classifier
z_new = rng.normal(Z_tr.mean(axis=0), Z_tr.std(axis=0), size=(360, 8))
def decode(z):
h = z
for i in (2, 3):
h = h @ P[2 * i] + P[2 * i + 1]
h = np.maximum(h, 0) if acts[i] == "relu" else 1 / (1 + np.exp(-h))
return h
nearest = lambda A: np.sqrt(((A[:, None, :] - Z_tr[None]) ** 2).sum(-1)).min(axis=1).mean()
print(f"distance to nearest training code: validation codes {nearest(Z_va):.2f}, random codes {nearest(z_new):.2f}")
print(f"classifier confidence: real validation images {clf.predict_proba(X_va).max(1).mean():.3f}, "
f"decoded random codes {clf.predict_proba(decode(z_new)).max(1).mean():.3f}")epoch 1 validation MSE 0.1058
epoch 10 validation MSE 0.0301
epoch 100 validation MSE 0.0189
PCA, 8 components: validation MSE 0.0244
logistic regression on raw 64 pixels: validation accuracy 0.967
logistic regression on PCA 8 codes : validation accuracy 0.903
logistic regression on AE 8 codes : validation accuracy 0.908
distance to nearest training code: validation codes 1.09, random codes 2.17
classifier confidence: real validation images 0.899, decoded random codes 0.656
Three results:
- Compression. After 100 epochs the validation reconstruction error is 0.0189 per pixel, against 0.0244 for PCA with the same 8 numbers per image. The nonlinear network uses its 8 numbers better than a linear projection can.
- Features. A logistic regression on the 8 learned codes reaches 0.908 validation accuracy, about the same as on 8 PCA components (0.903) and well below the raw 64 pixels (0.967). The code was trained to rebuild pixels, not to separate classes, so it keeps what is needed for reconstruction (stroke thickness, slant) along with class information. Autoencoder features help when labels are scarce and unlabelled data is plentiful. With a full labelled set, training on the labels directly wins.
- Generation. Codes drawn from a Gaussian with each unit's training mean and spread are, on average, 2.17 away from the nearest training code. Validation codes are only 1.09 away. Decoded random codes get a mean top-class probability of 0.656 from a pixel classifier, against 0.899 for real digits: many of them are smudges between classes. The encoder put the training codes on a thin, irregular set inside , and nothing in the loss asked it to fill a simple region you could sample from.
Denoising and sparse codes in NumPy
To make the comparison fair, all three models get an overcomplete code of 128 units, twice the input size. Without a penalty such a network can learn the identity and still look perfect on the reconstruction loss. The masking noise for the test is fixed, drawn once from seed 1. The noisy validation images are scored against their clean versions.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
def corrupt(x, rng, p=0.3): # masking noise: 30 % of pixels set to 0
return x * (rng.random(x.shape) > p)
def train(code=128, noise=False, l1=0.0, epochs=40, seed=0):
rng = np.random.default_rng(seed)
W1 = rng.normal(0, np.sqrt(2 / 64), (64, code)); b1 = np.zeros(code)
W2 = rng.normal(0, np.sqrt(1 / code), (code, 64)); b2 = np.zeros(64)
P = [W1, b1, W2, b2]; m = [0 * p for p in P]; v = [0 * p for p in P]; t = 0
for _ in range(epochs):
for idx in np.array_split(rng.permutation(len(X_tr)), 17):
x = X_tr[idx]; xin = corrupt(x, rng) if noise else x
z = np.maximum(xin @ W1 + b1, 0) # code
r = 1 / (1 + np.exp(-(z @ W2 + b2))) # reconstruction
gr = 2 * (r - x) / x.size * r * (1 - r) # target is the CLEAN x
gz = (gr @ W2.T + l1 * np.sign(z) / len(x)) * (z > 0) # L1 on the code
grads = [xin.T @ gz, gz.sum(0), z.T @ gr, gr.sum(0)]
t += 1
for k, g in enumerate(grads):
m[k] = 0.9 * m[k] + 0.1 * g; v[k] = 0.999 * v[k] + 0.001 * g * g
P[k] -= 3e-3 * (m[k] / (1 - 0.9 ** t)) / (np.sqrt(v[k] / (1 - 0.999 ** t)) + 1e-8)
return lambda x: (np.maximum(x @ W1 + b1, 0), 1 / (1 + np.exp(-(np.maximum(x @ W1 + b1, 0) @ W2 + b2))))
X_va_noisy = corrupt(X_va, np.random.default_rng(1))
print(f"noisy input itself: MSE to clean {np.mean((X_va_noisy - X_va) ** 2):.4f}")
for name, kw in [("plain, code 128", {}), ("denoising", {"noise": True}), ("sparse, L1 1e-3", {"l1": 1e-3})]:
enc = train(**kw)
z, r_clean = enc(X_va)
_, r_noisy = enc(X_va_noisy)
print(f"{name:16s} clean MSE {np.mean((r_clean - X_va) ** 2):.4f} noisy->clean MSE {np.mean((r_noisy - X_va) ** 2):.4f}"
f" active code units {np.mean(z > 1e-3) * 100:4.1f} %")noisy input itself: MSE to clean 0.0704
plain, code 128 clean MSE 0.0024 noisy->clean MSE 0.0494 active code units 84.7 %
denoising clean MSE 0.0131 noisy->clean MSE 0.0234 active code units 67.4 %
sparse, L1 1e-3 clean MSE 0.0100 noisy->clean MSE 0.0361 active code units 15.0 %
The plain overcomplete autoencoder reaches the lowest clean error, 0.0024, because it comes close to copying. Give it masked digits and it mostly copies the holes too: 0.0494, not far below the 0.0704 of the noisy input itself. The denoising model gives up some clean accuracy (0.0131) and roughly halves the damage on corrupted inputs, to 0.0234. The sparse model with keeps only 15.0 % of its code units above on a typical image, against 84.7 % for the plain model. Each image is described by a few active features out of 128, which is what makes sparse codes easier to inspect. With a much larger the code collapses and reconstruction fails, so is tuned on validation like any other regulariser.
The same in PyTorch (recorded): a convolutional autoencoder
Images call for convolutions (Convolution Layers). The encoder below has a stride-1 and a stride-2 convolution followed by a linear layer down to 8 numbers. The decoder mirrors it with a transposed convolution (ConvTranspose2d, kernel 4, stride 2, padding 1), which doubles the map back to . The masking noise is applied inside forward and only in training mode, so the same model is evaluated on clean or noisy inputs. This example is recorded and ran on the CPU.
import numpy as np
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
torch.manual_seed(0)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
X, y = load_digits(return_X_y=True)
X = (X / 16.0).astype(np.float32)
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
img = lambda a: torch.from_numpy(a).reshape(-1, 1, 8, 8).to(device)
class ConvAE(nn.Module):
def __init__(self, code=8):
super().__init__()
self.enc = nn.Sequential(nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), # 16 x 8 x 8
nn.Conv2d(16, 32, 3, stride=2, padding=1), nn.ReLU(), # 32 x 4 x 4
nn.Flatten(), nn.Linear(32 * 16, code))
self.dec = nn.Sequential(nn.Linear(code, 32 * 16), nn.ReLU(), nn.Unflatten(1, (32, 4, 4)),
nn.ConvTranspose2d(32, 16, 4, stride=2, padding=1), nn.ReLU(), # 16 x 8 x 8
nn.Conv2d(16, 1, 3, padding=1), nn.Sigmoid())
def forward(self, x, noise=0.0):
if self.training and noise > 0: # denoising: mask pixels of the INPUT only
x_in = x * (torch.rand_like(x) > noise)
else:
x_in = x
return self.dec(self.enc(x_in))
def fit(noise, epochs=60):
torch.manual_seed(0)
model = ConvAE().to(device)
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
xs = img(X_tr)
for epoch in range(epochs):
model.train()
for idx in torch.randperm(len(xs)).split(64):
loss = nn.functional.mse_loss(model(xs[idx], noise), xs[idx]) # target: clean image
opt.zero_grad(); loss.backward(); opt.step()
return model.eval()
print("device:", device, " parameters:", sum(p.numel() for p in ConvAE().parameters()))
gen = torch.Generator().manual_seed(1)
xv = img(X_va)
xv_noisy = xv * (torch.rand(xv.shape, generator=gen) > 0.3)
for noise in (0.0, 0.3):
model = fit(noise)
with torch.no_grad():
clean = nn.functional.mse_loss(model(xv), xv).item()
denoise = nn.functional.mse_loss(model(xv_noisy), xv).item()
z_tr, z_va = model.enc(img(X_tr)).numpy(), model.enc(xv).numpy()
acc = LogisticRegression(max_iter=2000).fit(z_tr, y_tr).score(z_va, y_va)
print(f"train noise {noise:.1f}: val MSE clean {clean:.4f} noisy->clean {denoise:.4f} logistic on codes {acc:.3f}")device: cpu parameters: 21865
train noise 0.0: val MSE clean 0.0126 noisy->clean 0.0496 logistic on codes 0.942
train noise 0.3: val MSE clean 0.0155 noisy->clean 0.0198 logistic on codes 0.911
The convolutional model has 21865 parameters. Trained without noise, it reaches a clean validation error of 0.0126 with the same 8-number code, and its codes give 0.942 accuracy with logistic regression, better than the NumPy MLP's 0.908. Trained with 30 % masking, its error on corrupted validation digits drops from 0.0496 to 0.0198, while the clean error rises a little (0.0155) and the codes become a little less linearly separable (0.911). Denoising buys robustness and pays for it in reconstruction detail. Whether that trade helps depends on the downstream task, so measure it on validation data.
Anomaly detection, one digit at a time (recorded)
A model trained only on normal data rebuilds unusual inputs badly, so the reconstruction error is an anomaly score. A fair test uses each class in turn as the anomaly. The autoencoder is trained on the training images of the other nine digits, then scores the whole validation set, where the held-out digit (35 to 37 images) is the positive class. ROC AUC measures how well the score ranks anomalies above normal images. A PCA model with 8 components is the baseline.
import numpy as np
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA
from sklearn.metrics import roc_auc_score
X, y = load_digits(return_X_y=True)
X = (X / 16.0).astype(np.float32)
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
def ae_scores(x_train, x_score, epochs=200):
torch.manual_seed(0)
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 _ in range(epochs):
for idx in torch.randperm(len(xt)).split(128):
loss = ((model(xt[idx]) - xt[idx]) ** 2).mean()
opt.zero_grad(); loss.backward(); opt.step()
with torch.no_grad():
xs = torch.from_numpy(x_score)
return ((model(xs) - xs) ** 2).mean(dim=1).numpy()
auc_ae, auc_pca = [], []
for c in range(10): # digit c is the "anomaly", never seen in training
x_train = X_tr[y_tr != c]
is_anom = (y_va == c).astype(int) # validation: 9 normal classes + class c
auc_ae.append(roc_auc_score(is_anom, ae_scores(x_train, X_va)))
pca = PCA(n_components=8).fit(x_train)
err = ((pca.inverse_transform(pca.transform(X_va)) - X_va) ** 2).mean(axis=1)
auc_pca.append(roc_auc_score(is_anom, err))
print("held-out digit: " + " ".join(f"{c:5d}" for c in range(10)))
print("AUC autoencoder:" + " ".join(f"{a:5.2f}" for a in auc_ae))
print("AUC PCA (8): " + " ".join(f"{a:5.2f}" for a in auc_pca))
print(f"mean AUC: autoencoder {np.mean(auc_ae):.3f} PCA {np.mean(auc_pca):.3f}")held-out digit: 0 1 2 3 4 5 6 7 8 9
AUC autoencoder: 0.98 0.94 0.97 0.90 0.96 0.96 0.92 0.97 0.86 0.83
AUC PCA (8): 0.95 0.75 0.94 0.79 0.96 0.96 0.92 0.94 0.85 0.85
mean AUC: autoencoder 0.929 PCA 0.893
Averaged over the ten splits, the autoencoder reaches an AUC of 0.929 and PCA 0.893, but the per-class picture is the real result. Unseen 1s are easy for the autoencoder (0.94) and hard for PCA (0.75). A likely reason: a 1 is a thin stroke with little ink, which a linear subspace learned from other digits can approximate, while the nonlinear decoder has never produced one. Unseen 9s (0.83 against 0.85) and 8s (0.86 against 0.85) are hard for both, because a 9 is close to a 4 or a 7 with a loop, and an 8 is close to a 3 or a 0. An anomaly made of familiar parts gets rebuilt well and is not detected. Report the per-class (or per-anomaly-type) spread along with the mean. This experiment trained 10 models for 200 epochs each. A shorter run of 80 epochs, tried while writing this lesson, gave a mean of only 0.867, below PCA. An undertrained autoencoder is a worse detector than the linear baseline.
Why a plain autoencoder is not a generator
A generator needs a distribution that is easy to sample and whose samples decode to realistic data. A plain autoencoder never defines one. Its loss only constrains the codes of training images, so the space between them is undefined, and a decoder that has never seen those regions returns blends. You saw the symptom above: random codes landed twice as far from any training code, and their decodings were much less digit-like. The fix is to make the encoder output a distribution for each image and to pull all of those distributions towards one fixed prior, . That is the variational autoencoder.
Pitfalls
- Judging an overcomplete model by its clean reconstruction. A near-zero error can mean the network learned to copy. Check it on corrupted or held-out data, or check what the codes are good for.
- Corrupting the target as well as the input. The denoising loss compares with the clean image. If the noisy image is the target, the model learns to reproduce noise.
- Noise left on at evaluation. Apply the corruption only in training mode (
self.training), as the convolutional example does, and corrupt evaluation data on purpose when you want to measure denoising. - One anomaly class, one number. Detection quality varies a lot by anomaly type (0.83 to 0.98 above). Thresholds for flagging belong on validation data, never on training errors, which are optimistically low.
- Expecting good features automatically. Reconstruction keeps everything that is visible, including nuisance factors. Compare codes against PCA and raw inputs, as done here, before adopting them.
Practice
- In the NumPy denoising example, the plain 128-unit model's error on corrupted inputs is 0.0494, while the corrupted inputs themselves are at 0.0704. Why does it improve on them at all if it has learned something close to the identity?
Answer
It is not exactly the identity. The sigmoid output, the ReLU code and 40 epochs of training leave it as a smooth function fitted to digit images. Inputs with holes lie off the training data, and the decoder's output is pulled a little towards typical pixel values, which partly fills the holes. Nothing in its loss rewards that, so the effect is small compared with the denoising model's 0.0234.
- Show that the L1 term with ReLU codes adds to the gradient of every active unit and nothing to inactive ones, as the line
gz = (gr @ W2.T + l1 * np.sign(z) / len(x)) * (z > 0)does.
Answer
With ReLU codes , so and for , which is . Multiplied by , and by because the code averages over the batch, it adds to the gradient coming from the decoder. The factor (z > 0) is the ReLU derivative, applied to the sum, so inactive units get no gradient from either term.
- You want to flag defective parts on a production line with an autoencoder trained on good parts. Which numbers from this lesson's anomaly experiment warn you about over-trusting a single validation AUC?
Answer
The per-class AUCs range from 0.83 to 0.98, so how detectable an anomaly is depends on how different it is from normal data. A defect type that looks like a mix of normal parts, like a 9 among 4s and 7s, can be close to undetectable. The 80-epoch run (mean 0.867, below PCA) shows that training length alone can flip the comparison with a baseline. Validate per defect type, compare with PCA, and set the threshold on validation data.
Test yourself
An overcomplete autoencoder (code larger than the input) reaches almost zero reconstruction error on validation images. What is the most likely explanation?
- It has learned an excellent compressed representation
- It has learned something close to the identity function, which needs no compression
- The validation set leaked into training
- The learning rate was too high
In a denoising autoencoder, what is the target of the reconstruction loss?
- The corrupted input
- The clean input
- The code
- Random noise
Why do random codes decoded by a plain autoencoder look less like digits than reconstructions do?
- The decoder is too small
- The loss only constrains the codes of training images, so the regions between them are never trained and no simple sampling distribution exists
- Random codes have the wrong dimension
- The sigmoid output saturates
Trained on nine digit classes and tested on the tenth, the autoencoder's anomaly AUC ranged from 0.83 to 0.98. What does the low end mean?
- The model is broken for that class
- Anomalies that resemble normal data are reconstructed well and are hard to detect by reconstruction error
- AUC cannot be computed for that class
- PCA always beats autoencoders