Overview
An autoencoder has two halves. The encoder turns a row of numbers into a much shorter list called the code, and the decoder tries to rebuild the original row from the code alone. Because the code is small, the network cannot copy the input. It has to find the few quantities that explain most of the variation in the data. No labels are needed, since the target is the input itself. A denoising autoencoder goes one step further: it is shown a damaged copy of the row and asked to return the clean one, which forces it to learn how the features depend on each other.
A short history
Autoencoders appeared in the 1980s alongside backpropagation, as networks trained to reproduce their own input through a narrow hidden layer. Geoffrey Hinton and Ruslan Salakhutdinov showed in 2006 that deep autoencoders could reduce dimensionality better than principal component analysis. Pascal Vincent and colleagues introduced the denoising autoencoder in 2008, which corrupts the input and trains the network to recover the clean version, giving more robust features.
How it works
- The encoder maps the input through tanh hidden layers to a linear code of
code_sizenumbers. - The decoder mirrors the encoder and maps back to a reconstruction with a linear output.
- For a denoising autoencoder, corrupt the input first: add Gaussian noise of standard deviation
noise_std, then set a sharemask_probof the values to zero. The target stays clean. - Compute the squared error between the reconstruction and the clean input, summed over features and averaged over rows.
- Backpropagate that error through the decoder and the encoder and update all weights with Adam.
- After training, use
encodefor the codes,predictfor reconstructions andreconstruction_errorto score how unusual a row is.
Watch out for
- If the code is as wide as the input, the network can learn to copy its input and the code tells you nothing. Keep
code_sizesmall or add corruption. - With no hidden layers the autoencoder is linear and finds the same subspace as PCA, at more cost and with less stability. Use PCA when a linear code is enough.
- The reconstruction error only flags rows unlike the training data. If the training set already contains many anomalies, the network learns to rebuild them and they are not flagged.
- Features on larger scales dominate the squared error, so the network spends its capacity on them. Standardise the columns first.
Use cases
When to use it
Non-linear dimensionality reduction, learning features without labels, removing noise from inputs, and anomaly detection through the reconstruction error.
In industry
- Manufacturing and operations
- Anomaly detection: a model trained on normal sensor readings rebuilds them well, so a high reconstruction error flags an unusual machine state.
- Payments
- Flagging unusual transactions by how poorly an autoencoder trained on ordinary activity can reconstruct them.
- Imaging
- Removing noise from scans or photographs with a denoising autoencoder trained on pairs of noisy and clean images.
Choosing it: what must hold
- Plenty of unlabelled examples of the kind of data you want to compress or model.
- Structure in the data that a small code can capture; pure noise cannot be compressed.
- For anomaly detection, training data that is almost entirely normal cases.
When to choose something else
| If | Use instead |
|---|---|
| A linear projection is enough, or you need a fast and explainable baseline | Principal component analysis (PCA) |
| You want to generate new samples from the latent space | A variational autoencoder (VAE) |
| You have labels for the task you care about | A supervised model such as an MLP |
Math foundations
Encoder and decoder
Two networks. compresses the input to a code with fewer numbers than the input has, and expands the code back to the input size.
Reconstruction loss
The squared distance between each row and its reconstruction, averaged over the rows. Training minimises this over the weights of both networks.
Corruption
The damaged input used by the denoising variant: noise is added, then each value is kept with probability and zeroed otherwise.
Denoising loss
The network reads the corrupted row but is scored against the clean one. Copying the input no longer gives a low loss.
Anomaly score
The per-row reconstruction error. Rows that follow the patterns of the training data are rebuilt well, so a large value marks an unusual row.
Symbols
- one input row
- the code, of length code_size
- the reconstruction of the input
- the encoder and the decoder networks
- the corrupted input
- Gaussian noise added to the input
- noise_std, the standard deviation of that noise
- mask of zeros and ones applied to the input
- mask_prob, the chance that a value is zeroed
- number of rows
Worked by hand
A linear autoencoder from 2 numbers to a code of 1 and back. The encoder weight is and the decoder uses the same vector, so and . Try a point on the line through and a point at right angles to it.
A point along the learned direction is rebuilt exactly. A point at right angles to it is lost completely and gets a large error. That is how the reconstruction error separates usual rows from unusual ones.
Visual example
Loading the example.
Try this
- Move the test point off the curve of data and watch its error e grow: that is the anomaly score.
- Set the code to 2 numbers: the network can now copy any point, so the error stops telling usual from unusual.
- Raise noise_std to 0.4 and see the reconstructions pull in toward the middle of the data.
Code sample
import numpy as np
from impl import Autoencoder
from config import AutoencoderConfig
rng = np.random.default_rng(0)
X = rng.normal(size=(300, 2)) @ rng.normal(size=(2, 8)) # 8 features that live on a 2-d plane
ae = Autoencoder(AutoencoderConfig(code_size=2, hidden_sizes=(), epochs=150)).fit(X)
codes = ae.encode(X) # (300, 2)
print(ae.reconstruction_error(X).mean()) # close to 0Read the implementation (122 lines)
"""Autoencoder: a network trained to reproduce its input through a narrow bottleneck.
NumPy only, manual backpropagation. With `noise_std` or `mask_prob` above zero it is a denoising autoencoder:
the input is corrupted, the target stays clean, so the network has to learn the structure of the data rather
than the identity map.
"""
from __future__ import annotations
import numpy as np
try:
from .config import AutoencoderConfig
except ImportError: # run from the template's own folder
from config import AutoencoderConfig
class Autoencoder:
"""Encoder: input -> hidden_sizes -> code. Decoder: the mirror image. Linear code and output layers."""
def __init__(self, config: AutoencoderConfig | None = None) -> None:
self.config = config or AutoencoderConfig()
self.weights: list[np.ndarray] = [] # weights[l]: (fan_in, fan_out), encoder layers then decoder layers
self.biases: list[np.ndarray] = []
self.loss_history: list[float] = [] # mean reconstruction error per epoch (against the clean input)
def _init_params(self, n_features: int) -> None:
cfg = self.config
rng = np.random.default_rng(cfg.seed)
sizes = [n_features, *cfg.hidden_sizes, cfg.code_size, *reversed(cfg.hidden_sizes), n_features]
self.weights = [rng.normal(0.0, np.sqrt(1.0 / a), size=(a, b)) for a, b in zip(sizes[:-1], sizes[1:])]
self.biases = [np.zeros(b) for b in sizes[1:]]
self._code_layer = len(cfg.hidden_sizes) + 1 # number of layers in the encoder
def _is_linear(self, layer: int) -> bool:
"""The code layer and the output layer have no activation."""
return layer == self._code_layer - 1 or layer == len(self.weights) - 1
def _forward(self, X: np.ndarray, start: int = 0, stop: int | None = None) -> list[np.ndarray]:
"""Activations of layers start..stop, the input to layer `start` first."""
acts = [X]
stop = len(self.weights) if stop is None else stop
for l in range(start, stop):
z = acts[-1] @ self.weights[l] + self.biases[l]
acts.append(z if self._is_linear(l) else np.tanh(z))
return acts
def corrupt(self, X: np.ndarray, rng: np.random.Generator) -> np.ndarray:
"""Apply the configured corruption: Gaussian noise of std `noise_std`, then zero a share `mask_prob`."""
cfg = self.config
out = X
if cfg.noise_std > 0:
out = out + rng.normal(0.0, cfg.noise_std, size=X.shape)
if cfg.mask_prob > 0:
out = out * (rng.random(X.shape) >= cfg.mask_prob)
return out
def loss_and_grads(self, X_in: np.ndarray, X_target: np.ndarray):
"""Mean squared reconstruction error and its gradients.
X_in: (n, d) network input (possibly corrupted). X_target: (n, d) what the output should be.
Returns (loss, weight gradients, bias gradients). The loss is the squared error summed over features
and averaged over rows.
"""
acts = self._forward(X_in)
n = len(X_in)
diff = acts[-1] - X_target
loss = float(np.sum(diff**2) / n)
delta = 2.0 * diff / n
gW, gb = [None] * len(self.weights), [None] * len(self.weights)
for l in range(len(self.weights) - 1, -1, -1):
gW[l] = acts[l].T @ delta
gb[l] = delta.sum(axis=0)
if l > 0:
delta = delta @ self.weights[l].T
if not self._is_linear(l - 1):
delta = delta * (1.0 - acts[l] ** 2)
return loss, gW, gb
def fit(self, X: np.ndarray) -> "Autoencoder":
"""Train with mini-batch Adam to reconstruct X. X: (n, d)."""
cfg = self.config
X = np.asarray(X, dtype=float)
self._init_params(X.shape[1])
rng = np.random.default_rng(cfg.seed + 1)
params = self.weights + self.biases
m = [np.zeros_like(p) for p in params]
v = [np.zeros_like(p) for p in params]
step = 0
self.loss_history = []
for _ in range(cfg.epochs):
order = rng.permutation(len(X))
total = 0.0
for start in range(0, len(X), cfg.batch_size):
clean = X[order[start:start + cfg.batch_size]]
loss, gW, gb = self.loss_and_grads(self.corrupt(clean, rng), clean)
total += loss * len(clean)
step += 1
for p, g, mi, vi in zip(params, gW + gb, m, v):
mi *= 0.9
mi += 0.1 * g
vi *= 0.999
vi += 0.001 * g * g
p -= cfg.learning_rate * (mi / (1 - 0.9**step)) / (np.sqrt(vi / (1 - 0.999**step)) + 1e-8)
self.loss_history.append(total / len(X))
return self
def encode(self, X: np.ndarray) -> np.ndarray:
"""Compress. X: (n, d) -> codes (n, code_size)."""
return self._forward(np.asarray(X, dtype=float), 0, self._code_layer)[-1]
def decode(self, Z: np.ndarray) -> np.ndarray:
"""Expand. Z: (n, code_size) -> reconstructions (n, d)."""
return self._forward(np.asarray(Z, dtype=float), self._code_layer)[-1]
def predict(self, X: np.ndarray) -> np.ndarray:
"""Reconstruct X (no corruption is applied). X: (n, d) -> (n, d)."""
return self.decode(self.encode(X))
def reconstruction_error(self, X: np.ndarray) -> np.ndarray:
"""Per-row squared error between X and its reconstruction, (n,). High values flag unusual rows."""
X = np.asarray(X, dtype=float)
return np.sum((self.predict(X) - X) ** 2, axis=1)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 6, run with
python3 -m unittest -v
Practice
Generate 300 rows with 8 features that lie on a 2-d plane, as in the template's README. Fit Autoencoder with code_size=2 and then with code_size=1, both with hidden_sizes=(), and compare the mean of reconstruction_error. Then add one row of pure random noise and check that its error stands out.
Check on learning
- Why does the bottleneck have to be narrower than the input for a plain autoencoder to learn anything useful?
A way to think about it
Ask what the cheapest way to reach zero loss would be if the code had as many numbers as the input.
- A denoising autoencoder is given an input with some values set to zero and must return the full row. What must it have learned about the data to do this well?
A way to think about it
A missing value can only be filled in from the other values. Think about what kind of relationship between features makes that possible.
- You train on normal machine readings and use the reconstruction error to find faults. A fault produces a large error on day one, but after you retrain on all recent data it no longer does. Why?
A way to think about it
Consider what the training set now contains, and what the network is rewarded for rebuilding.
- With no hidden layers the template finds the same subspace as PCA. What do the tanh hidden layers add, and when would you expect that to matter?
A way to think about it
PCA can only describe data lying near a flat plane. Picture data that lies along a curve.