MNIST Variational Autoencoder
The Decision
Restrict the latent space to two dimensions so that the learned structure can be inspected directly.
Takeaways
- Ten digit clusters form in the latent space, although the model is trained without labels.
- Fours and nines overlap almost completely, and the same pair is confused in reconstruction.
- A nearest-centroid rule in the two-dimensional space recovers the correct digit 69.8% of the time.
This project implements a variational autoencoder (VAE) that compresses 28 x 28 images of handwritten digits into two numbers and reconstructs each image from those two values alone. Whereas a standard autoencoder learns a fixed encoding for each image, a VAE learns a distribution over the latent space, which encourages continuity and allows new digits to be generated from unseen points.
The latent dimension was set to 2 so that the learned structure could be plotted and examined directly. This is an early project, and the bottleneck is a teaching constraint: it limits performance, but each claim below can be checked against a figure.
Source code: github.com/olivia-jackson-lambert/digit-variational-autoencoder
Data Exploration
MNIST contains 60,000 training images and 10,000 test images of handwritten digits, each 28 x 28 pixels in greyscale. A channel dimension was added, pixels were scaled to the range 0 to 1, and the training set was shuffled.
Building the Variational Autoencoder
The encoder maps each image to a distribution in the latent space, parameterised by a mean and a log-variance. The decoder maps a point sampled from that distribution back to an image.
Encoder
Input Layer
- Matches the 28 x 28 x 1 image shape.
Convolutional Layers
- 32, 64 and 128 filters provide sufficient capacity for MNIST while keeping the model small.
- A 3 x 3 kernel captures local stroke features such as curves and junctions without excessive smoothing.
- Strides of 1, 2 and 2 reduce the spatial resolution as the filter depth increases.
Flatten and Dense Layer
- The feature maps are flattened into a single vector.
- A 256-unit dense layer extracts further features before the bottleneck.
Latent Distribution
- Two parallel dense layers output
z_meanandz_log_var, the parameters of a Gaussian.
Sampling
The sampling layer draws a point from the encoder’s distribution using the reparameterisation trick:
\[z = \mu + \exp(0.5 \log \sigma^2) \odot \epsilon, \qquad \epsilon \sim \mathcal{N}(0, 1)\]
Because all of the randomness is contained in \(\epsilon\), which is treated as an input, the operation remains differentiable and gradients can propagate back through the encoder during training.
Decoder
Input Layer
- Takes the two latent values produced by the encoder.
Dense Layers
- Two hidden dense layers of 256 units each, mirroring the encoder.
- Dense layers connect every latent value to every region of the reconstructed image.
- ReLU activations expand the representation back towards the original size.
Output Layer
- A 784-unit dense layer with sigmoid activation produces pixel values between 0 and 1.
- The output is reshaped to 28 x 28 x 1 to match the input.
Loss Function
The training objective combines two terms that act in opposition:
- Reconstruction loss is binary cross-entropy summed over pixels and measures how closely the output matches the input.
- Kullback-Leibler (KL) loss measures the divergence of each encoded distribution from a unit Gaussian and encourages a continuous latent space.
With reconstruction loss alone, the model could place encodings anywhere and leave gaps between them; the KL term penalises this, which allows the space to be sampled meaningfully.
Training
The model was trained for 50 epochs with a batch size of 128 and the Adam optimiser, using the test set for validation.
| Loss component | Epoch 1 | Epoch 50 |
|---|---|---|
| Total | 188.0 | 136.6 |
| Reconstruction | 183.9 | 129.6 |
| KL | 4.1 | 7.0 |
| Validation total | 167.6 | 143.4 |
The KL term rises from 4.1 to 7.0 while reconstruction loss falls from 183.9 to 129.6, indicating that the model obtains better reconstructions by allowing the latent distribution to move further from the prior.
Training and validation loss diverge after approximately epoch 15, finishing at 136.6 and 143.4 respectively. Validation loss changes very little after epoch 25 (from 143.5 to 143.4), so the later epochs mainly improve the fit to the training set, and training could reasonably have been stopped earlier.
The Latent Space
Digit Clustering
Each digit class occupies a distinct region of the latent space, although no labels were used in training; the clustering arises from pixel structure alone.
Some overlap between classes is expected in a VAE. To quantify it, a Gaussian was fitted to each class and the Bhattacharyya coefficient was computed for every pair.
| Digit pair | Overlap | Digit pair | Overlap | |
|---|---|---|---|---|
| 4 and 9 | 0.950 | 7 and 9 | 0.671 | |
| 3 and 5 | 0.794 | 2 and 3 | 0.600 | |
| 5 and 8 | 0.740 | 0 and 1 | 0.002 | |
| 3 and 8 | 0.684 | 1 and 6 | 0.002 |
A coefficient of 1.0 would indicate that two classes are indistinguishable. Fours and nines reach 0.950, which is consistent with their shared form (a closed or nearly closed loop above a vertical stroke, differing mainly in whether the loop closes). Zeros and ones, which share little stroke structure, have a coefficient of 0.002.
A nearest-centroid rule in this space recovers the correct digit 69.8% of the time. This is well above chance (10%) but well below what a supervised classifier would achieve, which gives a rough indication of how much class information two dimensions can retain.
Reconstruction
The reconstructions are recognisable but blurred, and the errors are the more informative part of the figure. Both fours are reconstructed as nines and the five as a six. The confusion between four and nine corresponds to the pair with the highest overlap in the table above, here observed in individual images.
Generating Digits
Decoding points on a regular grid across the latent space illustrates what the model has learned.
In regions where classes overlap, the decoded digits are intermediate between shapes, whereas in regions dominated by a single class they are sharper, as with the 8s in the upper right and the 0s along the bottom.
Every point on the grid decodes to a digit-like image. A standard autoencoder would be expected to leave poorly decoded regions between clusters, so the grid is the most direct evidence here of continuity, although a baseline comparison (see Limitations) would be needed to confirm it.
Reproducibility
The original notebook was written in Keras against tensorflow.python.keras, which is no longer available in current TensorFlow releases, so it cannot be run as written. The figures on this page were produced by a PyTorch re-implementation with the same architecture, loss function and hyperparameters.
The re-implementation closely matches the original. Final training loss is 136.6 compared with 138.6 in the original, and the KL term rises from 4.1 to 7.0 compared with 4.8 to 6.8. The main difference is the gap between training and validation loss, which did not appear in the original run. The qualitative findings, including which digits overlap, are reproduced.
Limitations
Two latent dimensions is a presentation choice. It makes the space directly plottable but limits reconstruction quality to well below what a larger bottleneck would achieve, and the blurring in the generated grid is largely attributable to this constraint.
Sample quality is assessed visually. Loss values and visual inspection are the only measures used; no quantitative sample-quality metric was applied.
There is no baseline comparison. A standard autoencoder with the same architecture would show how much of the smoothness of the latent space is attributable to the KL term.
Next Steps
Latent dimensionality: Train with more latent dimensions, compare reconstruction loss, and use a method such as t-SNE to inspect structure that can no longer be plotted directly.
Conditional generation: Extend the model to a conditional VAE so that a specific digit can be requested.
Loss weighting: Vary the weight on the KL term to characterise the trade-off between sharp reconstructions and a continuous latent space.




