Generating is learning a distribution
What does it mean for a network to "generate" something new?
Lesson complete
If you like:
In part one, networks learned to decide: they look at a drawing like this one and answer: it is a seven.
No voice: the lesson advances on its own with subtitles.
The voice for this lesson is being recorded: for now it advances on its own with subtitles.
Review modeComment on this stepI finished the lesson
What you will achieve
- Explain the difference between classifying (drawing a boundary) and generating (knowing the distribution of the data and drawing new samples from it).
- Describe, piece by piece, how an autoencoder sums up an image in two numbers and rebuilds it, and what the latent space is.
- Recognize why a simple autoencoder’s plane has holes and how a VAE’s clouds fill them so that you can sample.
Key ideas
- Classifying means drawing a boundary between groups. Generating asks for more: knowing the distribution of the data, where it crowds and how far it reaches, to draw new samples.
- Sampling means drawing a new data point that follows the distribution: common things come out often and rare things seldom.
- The pixels of an image depend on each other: drawing them separately gives smudges. That is why each image is compressed into a few numbers that are enough to rebuild it.
- An autoencoder has two pieces: the encoder sums up the image in a code (here, two numbers) and the decoder rebuilds it. The plane of codes is the latent space.
- A simple autoencoder’s plane ends up untidy and full of holes. A VAE sums up each image as a cloud and gathers them in a known zone, so you can sample. The price: somewhat blurry images.
What many people believe
Common belief Generative AI cuts and pastes pieces of images it has stored: it is a collage.
What is true It learns a distribution: it stores weights, not images, and generates by drawing a random point and decoding it. What it generates resembles the data without copying any of it. The exception is memorization (mostly of images repeated many times in the data): a real failure that is measured and guarded against.
Check yourself
Four questions. No grade, no account: they just show whether the idea stuck.
Under the hoodFor those who want the math and the code. You do not need it to follow the course.
Classifying versus generating
A model that classifies learns : given the data, the label; the boundary is enough. A generative model learns the distribution of the data itself, , and lets you sample . It is usually trained by maximum likelihood:
The cloud of sevens
Each digit is measured as : the ink in its top half and the ink in its bottom half (each pixel is worth 0 to 1; each half has 32 pixels). The lesson’s ovals are a two-dimensional Gaussian fitted by maximum likelihood to the 179 sevens:
The small oval is and the large one is . In a two-dimensional Gaussian, and of samples fall inside them. To sample, take and , with (Cholesky). The boundary between sixes and sevens in the scene is the linear discriminant analysis one: the line where the two Gaussians, with their averaged covariance, give the same density.
Why each pixel on its own is not enough
Drawing each pixel from its own distribution amounts to assuming : independent pixels. For digits that is false (a stroke lights up its neighbors), which is why you get smudges. You need a model of how pixels vary together.
Autoencoder
An encoder and a decoder , trained together to minimize the reconstruction error:
The lesson’s models are tiny: with in the hidden layer and a sigmoid at the output (4,354 parameters), trained with gradient descent (Adam) on 1,500 images; another 297 were held back so the network could rebuild images it never saw. Mean error per held-out image by code size: 3.14 with 1 number, 2.34 with 2, 1.46 with 4, 0.95 with 8 and 0.54 with 16 (always guessing the mean image would give 4.71). With a linear decoder and squared error, an autoencoder learns the same subspace as PCA (Goodfellow et al., 2016, §14.1); nonlinear layers generalize it, and Hinton and Salakhutdinov (2006) showed that deep autoencoders learn codes that work much better than PCA.
Variational autoencoder (VAE)
We postulate a code with a known prior, (the “round zone”), and a decoder . The encoder returns a cloud, : its center and its size. During training a point is drawn with the reparameterization trick, which lets the gradient through:
What is maximized is a lower bound on (the ELBO):
The first term is the reconstruction error; the second is the penalty that pulls each cloud toward the standard zone. For diagonal Gaussians it has a closed form:
The loss used in the lesson is with (4,420 parameters). The two terms compete: reconstruction separates and shrinks the clouds; the penalty pulls them together and widens them. To generate: and . With a fixed-variance Gaussian decoder, the best reconstruction of a code is the average of the images that fit it: hence the blur. Kingma and Welling (2019, §2.8.2) attribute it to the fit never being perfect and note that it eases with more flexible inference and generative models.
Sampling with each model
The autoencoder defines no zone to sample from; the naive fallback is to draw uniform points in the box of its codes. A simple classifier (logistic regression trained on the same 1,500 images) labeled 3,000 samples from each model: the autoencoder gave 22% fours, 21% sixes and 0.7% eights; the VAE, between 6% and 14% of each digit (the real data has about 10% of each). With eight different seeds the result holds: the VAE always comes out more even (see train_toy.py).
In code
import numpy as np
# five sevens measured as (top ink, bottom ink): example
m = np.array([[12.0, 7.8], [10.4, 8.9], [11.3, 7.4], [9.6, 8.5], [10.9, 8.1]])
mu = m.mean(axis=0) # center of the cloud
cov = np.cov(m.T, bias=True) # shape of the oval (maximum likelihood: divide by N)
L = np.linalg.cholesky(cov) # L @ L.T == cov
rng = np.random.default_rng(0)
new = mu + rng.standard_normal((3, 2)) @ L.T # sampling: three new points from the cloud
print(mu.round(2).tolist(), new.round(1).tolist())
# [10.84, 8.14] [[10.9, 8.0], [11.4, 7.9], [10.4, 8.5]]
# A VAE cloud: center and size (one per number in the code)
c, s = np.array([0.8, -0.3]), np.array([0.5, 0.8])
kl = 0.5 * np.sum(c**2 + s**2 - np.log(s**2) - 1) # penalty against the standard zone N(0, I)
z = c + s * np.array([0.2, -1.0]) # a point drawn from the cloud (reparameterization trick)
print(round(float(kl), 4), z.round(2).tolist())
# 0.7263 [0.9, -1.1]
What comes next
VAEs were proposed independently by Kingma and Welling (2013) and by Rezende, Mohamed and Wierstra (2014). Generative adversarial networks (lesson 16) learn to generate without writing down a density: by competing. Diffusion (lesson 17) learns to remove noise, and its latent version works inside the compressed space of an autoencoder.
Decision lens
What this idea means if your job is to decide, not to code.
- What is generated reflects the mix of the training data, and sometimes distorts it: in the demo, the autoencoder almost never produced eights. Ask them to measure the mix of what is generated, not just show examples.
- Five flawless images are not evidence. Ask for random samples, with no selection, and a measure of quality and variety (for example, how many of a hundred attempts are usable and how many look alike).
- “It is not a collage” is the rule, not a guarantee: with large models and repeated data, memorization is documented. Ask about data deduplication, memorization tests, and the origin and license of what was used for training.
- Generating is sampling: the same instruction gives different results. If you need to reproduce a result, fix the seed and log the configuration; and remember that synthetic data carries no information that was not already in the original data.
Terms in this lesson
- Generative model A model that learns the distribution of its data (what is common, what is rare) and can therefore produce new, similar data. A model that classifies, by contrast, only learns the boundary between groups.
- Distribution The way the data is spread out: which values (or combinations of values) are common, which are rare, and which never appear. With two measures it looks like a cloud of points.
- Sampling Drawing a new data point that follows a distribution: common things come out often and rare things seldom. It is how a generative model generates. (Not to be confused with the audio samples of lesson 2.)
- Autoencoder A two-piece network: an encoder, which sums up each data point in a few numbers (the code), and a decoder, which tries to rebuild it from the code. It is trained to bring the reconstruction error down.
- Latent space The space of a model’s codes (“latent” means hidden): each data point is a point, and nearby points tend to be similar data. Any point can be decoded.
- Variational autoencoder (VAE) An autoencoder that sums up each data point as a cloud (center and size) instead of a point, and penalizes clouds that stray from a standard zone. That way the latent space has no holes and you can sample from it.
- Pixel The smallest dot of a digital image. In grayscale it is a number from 0 (black) to 255 (white); in color it is three numbers (red, green, and blue).
- Vector An ordered list of numbers. In machine learning, each example reaches the model as a vector.
- Feature One measurement of an example expressed as a number: the number of links in an email, the brightness of a pixel. The features of an example make up its vector.
- Weight (w) In a linear model, the number that multiplies the input: the slope of the line. It tells how much the prediction rises for each unit the input grows.
- Training data Examples, each with its correct answer, from which a model adjusts its parameters.
- Loss function A single number that summarizes how wrong a model is on its data. Training is the search for the parameters that make it as small as possible.
- Gradient descent A method that adjusts the weights step by step, always against the slope of the error (the gradient), until it reaches a bottom.
- Embedding A vector of numbers, learned from data, that represents something (a word, a sentence, an image) so that similar things end up close. Each word has a row in an embedding table.
- Vector space A space whose points are vectors. In an embedding space, the distance or angle between two points measures how alike their meanings are.
Full transcript
Sources
- Alpaydin, E., Kaynak, C. (1998). Optical Recognition of Handwritten Digits (UCI Machine Learning Repository, CC BY 4.0; datos de los dígitos de 8 × 8)
- Kingma, D. P., Welling, M. (2013). Auto-Encoding Variational Bayes
- Rezende, D. J., Mohamed, S., Wierstra, D. (2014). Stochastic Backpropagation and Approximate Inference in Deep Generative Models
- Kingma, D. P., Welling, M. (2019). An Introduction to Variational Autoencoders
- Hinton, G. E., Salakhutdinov, R. R. (2006). Reducing the Dimensionality of Data with Neural Networks
- Goodfellow, I., Bengio, Y., Courville, A. (2016). Deep Learning, capítulo 14 (Autoencoders) y capítulo 20 (Deep Generative Models)
- Alpaydin, E., Kaynak, C. (1998). Optical Recognition of Handwritten Digits (UCI Machine Learning Repository, CC BY 4.0)
- Carlini, N., Hayes, J., Nasr, M., Jagielski, M., Sehwag, V., Tramèr, F., Balle, B., Ippolito, D., Wallace, E. (2023). Extracting Training Data from Diffusion Models
CommentsThis lesson’s public conversation: questions, facts to check, ideas.
Comments live in GitHub Discussions, in the course’s public repository; writing one requires a GitHub account. They load from giscus.app when you open this section. The course reviewers read them, and if a change is accepted, it is applied in both languages. Open the thread on GitHub