Lesson 18 of 186 min
Autoencoders and latent space
An autoencoder squeezes each input into a few numbers and learns to draw it back, and those numbers make a space where alike inputs sit close.
After this lesson you can compress data into a small vector and rebuild it.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Prepare the digits
Scale the 64 pixels to values between zero and one. Use the digit labels to keep the split balanced. Set aside the labels once the split is made.
import numpy as np
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from torch import nn
from torch.utils.data import DataLoader, TensorDatasetdigits = load_digits()
pixels = digits.data.astype(np.float32) / 16
fit, aside = train_test_split(
pixels, test_size=0.2, stratify=digits.target, random_state=0
)
fit, aside = torch.from_numpy(fit), torch.from_numpy(aside)Train the encoder and decoder
Each picture is its own training target. The encoder squeezes the pixels to a code of the requested width. The decoder draws back all 64 pixels.
def train_epoch(model, batches, optimizer):
for (x,) in batches:
optimizer.zero_grad()
nn.functional.mse_loss(model(x), x).backward()
optimizer.step()def train_autoencoder(width):
torch.manual_seed(0)
encoder = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, width))
decoder = nn.Sequential(nn.Linear(width, 32), nn.ReLU(), nn.Linear(32, 64), nn.Sigmoid())
model = nn.Sequential(encoder, decoder)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
batches = DataLoader(TensorDataset(fit), batch_size=32, shuffle=True)
for _ in range(200):
train_epoch(model, batches, optimizer)
return model.eval()torch.set_num_threads(4)
model = train_autoencoder(3)Flag pictures with a large reconstruction error
Average the squared pixel errors for each picture. The largest values show you which pictures to inspect. A valid but unfamiliar drawing can score high.
@torch.inference_mode()
def squared_miss(model, x):
return (model(x) - x).square().mean(dim=1)
miss = squared_miss(model, aside)
print(f"{miss.mean():.4f}", miss.argsort(descending=True)[:4].tolist())0.0305 [179, 291, 140, 209]
Set the threshold at the first half's 95th percentile. Apply it to the other half. Flagged indices start at zero within that second half.
calibration, review = miss.split(180)
threshold = calibration.quantile(0.95)
flagged = (review > threshold).nonzero(as_tuple=True)[0]
print(f"Threshold: {threshold:.4f}. Flagged: {len(flagged)} of {len(review)}.")Threshold: 0.0614. Flagged: 11 of 180.
Use a sparse code to inspect model activations
A sparse autoencoder can use a wide code and encourage each input to activate just a few entries. Anthropic applied this to activations from Claude 3 Sonnet's middle layer and found a feature that responded to the Golden Gate Bridge. This cell illustrates the training objective on a small tensor. The second term penalizes large code activations.
torch.manual_seed(0)
features = torch.randn(8, 4)
encode = nn.Sequential(nn.Linear(4, 16), nn.ReLU())
decode = nn.Linear(16, 4)
codes = encode(features)
reconstruction = nn.functional.mse_loss(decode(codes), features)
loss = reconstruction + 0.1 * codes.abs().mean()
loss.backward()
print(tuple(codes.shape), bool(loss > reconstruction))(8, 16) True
See what a straight-line bottleneck can keep
With a linear encoder and decoder, centered data and squared error, the best reconstruction uses the same subspace as PCA. The code may use different coordinates within that space. PCA gives a benchmark for a three-number linear code. The network in the video uses ReLU, so it can learn a curved representation.
from sklearn.decomposition import PCA
pca = PCA(n_components=3).fit(fit)
back = pca.inverse_transform(pca.transform(aside))
print(f"{np.mean((back - aside.numpy()) ** 2):.4f}")0.0451
Keep the picture in a grid
Convolutions let the encoder work with nearby pixels in a photo. A stride of two halves the grid's height and width in this example. A transposed convolution gets back to the input size. Train the two layers together to make the drawing match the input.
photo = torch.rand(1, 3, 32, 32)
encode_grid = nn.Conv2d(3, 8, kernel_size=4, stride=2, padding=1)
decode_grid = nn.Sequential(
nn.ConvTranspose2d(8, 3, kernel_size=4, stride=2, padding=1),
nn.Sigmoid(),
)
grid = encode_grid(photo)
print(tuple(grid.shape), tuple(decode_grid(grid).shape))(1, 8, 16, 16) (1, 3, 32, 32)
Run on Python 3.13, PyTorch 2.15.0, scikit-learn 1.9.1. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: What hidden layers learn
The network was trained only to name the digits. Yet its layer of 3 now puts each digit in a region of its own. Why did it group them, when nobody asked?
2 of 3
With 64 numbers in its middle, an autoencoder draws the digits back almost perfectly. With only 3, it draws them a little blurred. Which one learned more about digits?
3 of 3
A batch of 32 digits, each 64 pixels, goes through the encoder, down to 3 numbers each, and then through the decoder. What shape is the drawing that comes out?
The ideas in this lesson
- Autoencoder
- An encoder squeezes data into a few numbers, a decoder draws it back: the input is its own answer.
- Latent space
- The space of the codes: alike inputs land close, and a point is drawn well only near the codes.
It leans on
- Diffusion models
Transcript
What the video says, part by part. Press a time to watch from there.
A few numbers
Here's a puzzle. Can a network turn a picture into just a few numbers? And then draw the picture back from them? AI image apps work in a small space like that. So what do those few numbers hold?
Through three numbers
Let's try it. Each digit is sixty-four pixels. It goes through just three numbers, and a network draws the picture back from them. After training, what comes out? The digits, a little blurred? Gray blobs, all alike? Or perfect copies?
Encoder, code, decoder
The network is really two networks, in a row. The first, the encoder, goes down from sixty-four pixels to three numbers. Those three numbers are the code. The second, the decoder, goes back up from the code to sixty-four pixels. Train the pair to draw back its own input. The loss is the squared miss between the picture and its drawing. The input is its own answer. So no labels are needed.
Drawn back
So, your guess. After two hundred epochs, the pictures set aside come back... as their digits, a little blurred. The squared miss is about zero point zero three. Always drawing the average picture would miss by more than twice as much.
PCA can squeeze the pixels to three numbers too, but only along straight lines. It misses more: about zero point zero four five.
The network's neurons have a bend, ReLU, so it can squeeze along curves, not just straight lines. That's why its three numbers hold more.
An autoencoder
An encoder, a code, a decoder, and the input as its own answer. That's called an autoencoder.
The squeeze
So why squeeze at all? With just one number, it misses by almost twice as much. A blur. With no squeeze at all, it misses by almost nothing. So which one learned the most about digits?
The one with three. One number can't hold enough to draw a digit. And with no squeeze, the code is just the picture again. It only copies the pixels. So the goal is a small code that still draws the digit. It's like describing a face over the phone in a few words. You keep what matters. Only here, the network finds its three numbers by itself.
The latent space
An autoencoder squeezes each picture into a code of three numbers. Three numbers make a point, in a space we can turn. The space of the codes is called the latent space.
Latent means hidden. And the digits gather... even though the network never saw a label.
Take any picture and the ten codes nearest to its own.
Seven in ten are its digit. Points thrown at random would give one in ten.
Why alike lands close
Why would they gather?
Two codes that are close get drawings that look alike. So two zeros that look alike are easiest to draw back when their codes are close.
Any point draws
And you can hold any point, and the decoder draws it. Start from the middle of the zeros, and walk toward the sixes. The drawing changes faster than the walk. A third of the way along, it's already half a zero and half a six. Keep walking, and it turns into a six.
Empty places
And a point far from every code? What does that draw?
A shape that isn't a digit. The decoder only learned to draw where the pictures' codes are. The rest of the space is empty. A program that makes new pictures needs a space with no empty places. So image generators train their autoencoder to fill its space.
Image generators
And that's where image generators make their pictures.
One image generator's autoencoder turns a large photo's three million numbers into half a million.
That's far more than three, but still six times fewer to work on.
The generator draws there, and the decoder turns the code into the photo.
In code
In code, the encoder and the decoder are two small networks, two layers each. The loss is the squared miss between the drawing and x, the input. So what's the label here?
x itself.
And here's a use for it. The network learned to draw back pictures like the ones it learned from.
So the pictures it draws back worst are the odd ones. A one with a wide hook, a two written like an eight. They miss by about four times the usual. That's how you find odd data.
Squeeze and draw back
So an autoencoder squeezes data into a few numbers, and draws it back. In its latent space, things that look alike sit close. And it only draws well near the codes it learned.
The lab
That's the end of this unit. In its lab, you train an autoencoder with no labels. Then you reuse it to read digits from ten examples of each.
Draw it back
An autoencoder turns a picture into a few numbers. Then it draws it back. Now try it on this lesson's page, and take the quiz. Walk from a one to a seven.
You use this lesson in Lab 7: Digits from ten labels a kind, which comes next.
Facts last checked on .
