An autoencoder (AE) is a neural network that learns to compress an input and reconstruct it. Its encoder maps the input to a smaller representation in latent space; its decoder uses that representation to produce a reconstruction. Training reduces the difference between the original and reconstructed inputs. Because each input supplies its own reconstruction target, an AE can learn representations from unlabeled data. section 7.1.1 section 7.0
A standard AE maps an image to a deterministic point in latent space. A variational autoencoder instead encodes a probability distribution. The simpler AE makes the compression-and-reconstruction loop a useful starting point before working with variational autoencoders. section 7.1.2 section 7.0
For handwritten digits, build and train the loop in small steps:
- Load MNIST’s 60,000 training images and 10,000 test images. Convert pixel values from 0–255 to tensors in the range 0–1, then make batches of 32. section 7.2.1
- Flatten each 28 × 28 grayscale image into 784 values. Dense layers compress it through 200 hidden values to a 20-value latent vector; decoder layers expand that vector back to 784 output values. section 7.2.2
- Compare output pixels with input pixels using squared reconstruction error, backpropagate the loss, and update the model with Adam. The example trains for 10 epochs rather than tuning against a validation set. section 7.2.2
Check what the model learned
Keep one test image for each digit, 0 through 9, and plot the originals above their reconstructions after each epoch. Before training, the reconstructions look like noise. This side-by-side check makes improvement visible without treating reconstruction loss as the only measure. section 7.2.2
Figure 7.3 The architecture of an AE and the steps to train one to generate handwritten digits. An AE consists of an encoder (middle left) and a decoder (middle right). In each iteration of training, images of handwritten digits are fed to the encoder (step 1). The encoder compresses the images to deterministic points in the latent space (step 2). The decoder takes the encoded vectors (step 3) from the latent space and reconstructs the images (step 4). The AE adjusts its parameters to minimize the reconstruction loss, the difference between the originals and the reconstructions (step 5).
Follow one image through encoding, its deterministic latent vector, decoding, and the reconstruction-loss update. section 7.1.2
Compression can discard information, leaving imperfect reconstructions. Dense layers suit this small grayscale-digit example; higher-resolution color images usually call for convolutional layers in the encoder and decoder. section 7.1.1 section 7.1.2











