Deep Learning · Representation Learning
An autoencoder learns to reconstruct data through an internal representation. That simple objective can support compression, denoising, feature learning and anomaly detection—but only when the architecture or training task prevents meaningless copying. We will calculate reconstruction loss, compare bottlenecks and regularization, set up anomaly scoring, and derive the sampling and KL terms that turn a deterministic autoencoder into a variational one.
Learning Without a Separate Class Label
Imagine thousands of machine-vibration windows but no labels saying which internal patterns matter. We can create a training target from the data itself: present a window x and ask a network to reproduce it as x̂. The labels are therefore not human classes; the target is the original signal or a clean version of it.
The encoder maps input x to a latent code z. The decoder maps z back to reconstruction x̂. If the code or training task is constrained appropriately, reconstruction forces z to preserve regular structure in the data.
An autoencoder learns an input → code → reconstruction journey
Only the reconstruction is compared with the target during basic training.
input x
encoder fθ
→
compress useful structure
latent code z
bottleneck
decoder gφ
→
reconstruct the input
output x̂
Reconstruction Loss Measures What Was Lost
For continuous, scaled features, mean squared error (MSE) is a common starting reconstruction loss. It subtracts each reconstructed value from its original, squares the difference so positive and negative errors cannot cancel, then averages so examples with different feature counts remain comparable. The output activation and loss must match the data range and likelihood assumption; binary cross-entropy is not automatically correct merely because pixels were scaled to [0,1].
Mean squared reconstruction error
Lrecon = (1/d) Σj=1d(xj − x̂j)²
d is the number of reconstructed values; xj comes from the training example, x̂j is produced by the decoder, and the loss is calculated from them—not selected by the developer.
A three-feature reconstruction
Use teaching input x=[1.0,0.5,0.0] and a hypothetical decoder output x̂=[0.8,0.4,0.1]. In a real run, x comes from the dataset and x̂ changes as training changes the network weights.
errors
[1−0.8, .5−.4, 0−.1]
= [0.2,0.1,−0.1]
squared errors
[0.04,0.01,0.01]
sum = 0.06
MSE = 0.06/3
= 0.02
Interpretation: the average squared reconstruction miss is 0.02 on this scale. Whether that is good requires comparison with validation data and a task baseline.
Why a Powerful Autoencoder Can Learn to Copy
If encoder and decoder have enough capacity and an unconstrained code, the easiest solution can approach an identity function: pass every detail through without discovering reusable structure. Low training reconstruction error alone therefore does not prove that the latent code is meaningful.
Narrow bottleneck
Use fewer latent dimensions so the code cannot carry every raw value.
Too narrow can underfit.
Sparse activity
Add a penalty so only a small subset of latent units activates per example.
Penalty strength controls the trade-off.
Denoising task
Corrupt the input but reconstruct the clean target, so copying noise is not rewarded.
Corruption must preserve the desired content.
Denoising Changes the Learning Question
A denoising autoencoder learns “recover the clean structure from a corrupted observation,” not simply “copy the input.” For scanned documents, corruption might simulate speckle, fading or sensor noise. The noisy version is the network input x̃, while the original clean item remains the target x.
A denoising autoencoder receives corruption but targets clean data
noisy input x̃
+
decoder
reconstruction x̂
clean training target x
Anomaly Detection Uses Error Carefully
If an autoencoder is trained mostly on normal machine behavior, it may reconstruct familiar patterns well and unfamiliar patterns poorly. A reconstruction score can then flag unusual windows. This is a heuristic, not a law: a high-capacity model may reconstruct anomalies too, and harmless distribution shift may raise error.
score(x) = (1/d) Σ(xj − x̂j)²
flag anomaly if score(x) > τ
τ is an operational threshold chosen on held-out normal and, when available, representative anomaly examples.
Reconstruction error can become an anomaly score
Evaluate precision–recall and alert burden across thresholds. Split time-series data chronologically or by equipment unit to avoid near-duplicate windows crossing train and test sets.
Autoencoder Variants Solve Different Constraints
| Variant | Main constraint/change | Useful starting scenario | Important limitation |
|---|---|---|---|
| Undercomplete | Latent dimension smaller than input | Compression/feature learning baseline | May discard task-relevant detail |
| Sparse | Penalty encourages few active code units | Interpretable-ish specialized features | Sparsity strength needs tuning |
| Denoising | Corrupted input, clean target | Noise removal and robust representation | Learns only corruption represented in training |
| Convolutional | Spatial convolutions in encoder/decoder | Images and spatial signals | Upsampling can create artifacts |
| Sequence | RNN/Transformer encoder and decoder | Time series or sequential reconstruction | Masking and length handling are critical |
| Variational (VAE) | Distribution parameters and latent sampling | Smooth probabilistic generation/representation | Reconstructions may be blurrier; posterior collapse |
A Variational Autoencoder Learns a Distribution
An ordinary autoencoder maps each input to one code. Empty regions between training codes may decode unpredictably, so arbitrary sampling is not guaranteed to produce plausible data. A Variational Autoencoder (VAE) asks the encoder for parameters of a distribution—commonly mean μ and diagonal variance σ²—then samples a latent z for the decoder.
A variational autoencoder encodes a distribution, then samples
qφ(z|x)
μ(x)
log σ²(x)
ε~N(0,I)
pθ(x|z)
VAE objective for one example
L = Lreconstruction + β DKL(qφ(z|x) ‖ p(z))
The reconstruction term rewards explaining x from z. The KL term measures how far the encoder's distribution qφ is from a chosen prior p(z), often N(0,I); adding it discourages isolated, irregular latent regions. β is a developer-chosen hyperparameter that multiplies this regularization before addition. β=1 gives the usual VAE objective; larger or smaller values change the reconstruction–regularity trade-off.
Sampling and KL Divergence With Numbers
One latent dimension
For a visible calculation, assume the encoder produced μ=0.5 and σ=0.8, then use one illustrative random draw ε=0.25 from N(0,1). In real training μ and σ are network outputs for each input, while ε is freshly sampled by the framework.
Reparameterized sample
z=μ+σε
=0.5+(0.8×0.25)
=0.70
Multiply to scale unit noise, then add μ to shift its centre.
KL to N(0,1)
KL=½(μ²+σ²−1−ln σ²)
=½(0.25+0.64−1−ln 0.64)
≈½(0.336)=0.168
This closed form compares the shifted, scaled encoder distribution with the unit-normal prior.
Interpretation: z remains random, but gradients can flow through μ and σ because ε contains the sampling randomness. The positive KL cost reflects that N(0.5,0.8²) differs from the unit-normal prior.
A Small Denoising Autoencoder in PyTorch
This example assumes 28×28 grayscale inputs scaled to [0,1]. Gaussian noise creates x̃; the clean batch x is the target. The final sigmoid matches the chosen [0,1] output range, while MSE measures pixel reconstruction.
import torch
from torch import nn
class DenoisingAutoencoder(nn.Module):
def __init__(self):
super().__init__()
self.encoder = nn.Sequential(
nn.Flatten(),
nn.Linear(28 * 28, 128), nn.ReLU(),
nn.Linear(128, 32),
)
self.decoder = nn.Sequential(
nn.Linear(32, 128), nn.ReLU(),
nn.Linear(128, 28 * 28), nn.Sigmoid(),
)
def forward(self, x):
z = self.encoder(x)
return self.decoder(z).view(-1, 1, 28, 28)
model = DenoisingAutoencoder()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
loss_fn = nn.MSELoss()
for clean_images, _ in train_loader:
noisy_images = (clean_images + 0.25 * torch.randn_like(clean_images)).clamp(0, 1)
reconstructed = model(noisy_images)
loss = loss_fn(reconstructed, clean_images) # clean target
optimizer.zero_grad()
loss.backward()
optimizer.step()Where the numbers come from
28×28 and one channel come from the image data, so flattening calculates 784 input values. The 128 hidden units, 32-value code, noise scale 0.25 and learning rate 0.001 are developer-selected hyperparameters to validate—not universal defaults.
What the operations do
randn_like samples Gaussian noise with the image shape; multiplying controls its strength, adding corrupts the input, and clamp restores the valid [0,1] range. The model receives noisy pixels but MSE compares its reconstruction with clean pixels, so training rewards noise removal.
For images, a convolutional encoder/decoder usually preserves spatial structure better than flattening; this dense network keeps the first implementation easy to trace.
Diagnose the Representation, Not Just the Loss
| Symptom | Likely cause | What to try |
|---|---|---|
| Near-perfect reconstructions but useless codes | Identity-like copying through excessive capacity | Narrow/regularize the code, add denoising, evaluate downstream utility |
| Everything reconstructs as an average | Underfitting, wrong output/loss, or optimization problem | Inspect scale and activations; overfit a tiny clean set; increase capacity carefully |
| Anomaly detector flags a new machine type | Normal validation data misses deployment diversity | Retrain/condition by domain and set thresholds per justified group |
| Anomalies reconstruct too well | Decoder generalizes or copies too broadly | Reduce capacity, use robust representation objectives, compare one-class alternatives |
| VAE ignores z | Posterior collapse; decoder too powerful or KL pressure too strong | Monitor per-dimension KL, anneal β, weaken decoder or use free-bits-style methods |
| Generated samples are poor despite low reconstruction loss | Deterministic latent gaps or VAE trade-off imbalance | Use a generative objective and evaluate sample quality separately |
What an Autoencoder Can—and Cannot—Promise
Reconstruction preserves what the chosen loss rewards. Pixel MSE may prioritize average colour over perceptual sharpness; feature MSE may preserve different properties. A low-dimensional code is not automatically interpretable, independent or useful for a downstream task. Neural compression also includes model storage and inference cost, not just code width.
Treat denoising, anomaly scoring, dimensionality reduction and generation as separate objectives with separate validation. An architecture called “autoencoder” does not make one model good at all four.
The Complete Autoencoder Picture
- The encoder creates z; the decoder reconstructs x̂; both learn from reconstruction error.
- A bottleneck, sparsity penalty or denoising task is needed to discourage unhelpful copying.
- Reconstruction loss, data scale and output activation must describe the data appropriately.
- Anomaly detection requires held-out threshold selection and must account for distribution shift.
- A VAE encodes μ and σ, samples with z=μ+σε, and balances reconstruction with KL regularization.
- Judge representations by the real downstream goal, not training loss alone.