Autoencoders
Neural networks that learn compressed codes by reconstructing their input; from PCA to VAEs.
Animated explanation
The idea
An autoencoder is a neural network trained to copy its input to its output through a bottleneck: a layer much smaller than the input. Because the bottleneck cannot hold everything, the network is forced to learn which features matter most to rebuild the data.
The first half (encoder) maps data to a compact code; the second half (decoder) maps the code back. With linear layers and squared error, the code spans exactly the PCA subspace. With non-linear layers it can unfold curved manifolds. Because they need no labels, autoencoders are used for compression, denoising, anomaly detection (normal data reconstructs well, anomalies don't), pretraining, and, in the variational form, generating new data.
Linear autoencoders are PCA
With encoder (k × d), decoder (d × k), no activations and squared error, the optimal reconstruction is the projection onto the top- principal subspace. The weights need not be orthonormal components, but they span the same space. Non-linearities are what make autoencoders more expressive than PCA.
Avoiding the identity
An overcomplete autoencoder (code larger than input) can learn to copy without learning anything. Constrain it: a narrow bottleneck, a sparsity penalty, noise on the input (denoising), or a penalty on the encoder's sensitivity (contractive). The variational autoencoder makes the code a Gaussian distribution and adds a KL penalty, so the code space is smooth and can be sampled.
The algorithm, step by step
- 1Choose the architecture: encoder layers shrinking to a code of size k, decoder mirroring it.
- 2Forward: , .
- 3Loss: mean squared reconstruction error (or cross-entropy for binary data).
- 4Train with mini-batch gradient descent (Adam); use the encoder output as features or the error as an anomaly score.
The maths
Reconstruction objective
Linear AE gradient (W = W_d W_e)
VAE evidence lower bound
Strengths and weaknesses
Strengths
- Learns non-linear compressed representations without labels
- Natural anomaly detector via reconstruction error
- Variational versions generate new samples
Weaknesses
- Needs tuning and data like any neural network
- Codes are not ordered or orthogonal like PCA
- Can learn trivial copies if unconstrained
Reach for it when…
Check your understanding
Lambdian Lab
A linear autoencoder rediscovers PCA
Train a linear autoencoder on centred data by gradient descent and compare it with PCA.
- reconstruct(X, We, Wd).
- train_linear_ae(X, k, lr, epochs, seed): We (k × d) and Wd (d × k) initialised N(0, 0.1²); full-batch gradient descent on the mean squared error (mean over rows of the squared norm); return (We, Wd, losses).
- subspace_angle(A, B): the largest principal angle in degrees between the column spaces of A and B (use QR, then the SVD of ).