A variational autoencoder (VAE) learns to reconstruct images while shaping a latent space from which new images can be generated. Unlike a classical autoencoder, which encodes an image as a vector, its encoder produces two vectors describing a probability distribution. A point sampled from that distribution goes to the decoder, which produces an image. section 17.1.2 section 17.1.3
Figure 17.4 A VAE maps an image to two vectors, z_mean and z_log_var, which define a probability distribution over the latent space, used to sample a latent point to decode.
Follow the image through the encoder’s mean and log-variance outputs, the sampled latent point, and the decoder. section 17.1.2
Generate handwritten digits
A Keras VAE for MNIST uses 28 × 28 digit images and a two-dimensional latent space. Its convolutional encoder outputs z_mean and z_log_var. A sampling layer draws random noise and computes z_mean + exp(0.5 × z_log_var) × noise; the decoder turns the resulting point into a 28 × 28 image. After training on normalized digits, pass a grid of two-dimensional points to the decoder to see how the generated digits vary across the space. section 17.1.3
The implementation has three practical parts:
- Encode with strided convolutions and produce separate mean and log-variance vectors. Strides preserve the location information needed to reconstruct an image. section 17.1.3
- Sample a latent point using the mean, log variance, and random noise. section 17.1.3
- Decode by reshaping the latent point and using convolutional layers to recover the input image dimensions. A custom compute_loss() handles training with the input image as the reconstruction target. section 17.1.3
The resulting continuous, structured latent space is useful for image editing and smooth transitions between images. VAEs also support reconstruction, but diffusion models are the stronger choice here for high-fidelity image generation. section 17.1.2 section 17.4












