Search

Search papers and lessons

Generative Model

Level 3 · 12 min read

A generative model learns the probability distribution of the data itself, so it can score how plausible an example is and produce new examples that look like the training set.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Discrete math
  • Generative models
  • Inference
  • Sign in to see your progress

TL;DR

A generative model is a probability model of the data itself. Given a family of possible datasets, such as photographs of faces or sentences in English, it assigns each possible example a probability, with plausible examples getting high values and nonsense getting low ones. Because it can do this, it can do two things a simpler model cannot: score how typical a new example is, and draw new examples from the same distribution.

The alternative is a discriminative model, which only learns a rule for a label given an input, such as "is this email spam?". It can answer that one question well, but it has no picture of what emails look like in general.

Where you'll see it: in language models that predict the next word, in image generators that turn a text prompt into a picture, and in anomaly detectors that flag inputs the model finds unlikely.

Intuition

A model that knows what the data looks like

Think of a sommelier who can taste a wine and say whether it is a plausible Burgundy, or whether something is off. Now think of a sommelier who can also describe, from scratch, a wine that a Burgundy grower might plausibly make. The first skill is recognition. The second is generation. A generative model has both, because to generate convincingly it must already know which outcomes are likely and which are not.

A discriminative model is the first sommelier only, and only for one question. Show it a bottle and it answers "red or white?". It may do that very accurately, yet it could not tell you what a red wine is.

The distinction matters because the world is full of questions that are not labels. "Write a paragraph about rivers" has no fixed set of answers to pick from. To write one, the system must hold a distribution over paragraphs and sample from it. That is what a generative model does.

flowchart LR
  subgraph Discriminative
    X1[Input x] --> M1[Model learns p of y given x] --> Y1[Label y]
  end
  subgraph Generative
    D[Training data] --> M2[Model learns p of x] --> S[Score any x]
    M2 --> G[Sample new x]
  end

Why learn the whole distribution at all

Learning the full distribution is harder than learning a boundary between classes. A boundary only has to be right where the classes meet. A full distribution has to say something sensible about every input, including inputs the model has never seen. The payoff is flexibility. Once you have p(x)p(\mathbf{x}), you can ask for samples, fill in missing pixels, estimate how surprising a new example is, or combine the model with a classifier. Most of the modern systems in this graph are one of these ideas, scaled up.

The math

Setup

Let x\mathbf{x} be one example (an image as a vector of pixel values, or a sentence as a sequence of tokens). Let θ\theta be the parameters of the model, which are the numbers the training process adjusts, such as the weights of a neural network. A generative model is a family of distributions pθ(x)p_\theta(\mathbf{x}) indexed by θ\theta. Each choice of θ\theta gives one distribution over all possible x\mathbf{x}.

Definition: Generative model

A generative model is a parametric family {pθ(x):θ∈Θ}\{p_\theta(\mathbf{x}) : \theta \in \Theta\} of probability distributions over the space of data x\mathbf{x}. For discrete data the density is replaced by a probability mass function. A trained generative model is one value of θ\theta chosen so that pθp_\theta fits the observed data.

Two properties are required. The values must be non-negative, and they must integrate (or, for discrete data, sum) to 1 over all x\mathbf{x}. These constraints are what make the model a distribution, and they are also why designing one is hard. A neural network with arbitrary outputs will not satisfy them unless its architecture is built to.

Training by maximum likelihood

Suppose the training set is D={x1,…,xn}\mathcal{D} = \{\mathbf{x}_1, \dots, \mathbf{x}_n\}, assumed to be independent samples from the unknown true distribution. The standard training rule is maximum likelihood: choose θ\theta to maximise the log-likelihood

ℓ(θ)=∑i=1nlog⁡pθ(xi).\ell(\theta) = \sum_{i=1}^{n} \log p_\theta(\mathbf{x}_i).

Maximising ℓ\ell pushes probability mass toward the training examples. Dividing by nn gives an average, and the expression then reads as an expected log-probability under the data, which is a cross-entropy between the data distribution and the model. Minimising the negative average log-likelihood is the same as minimising a cross-entropy, so most generative training is supervised learning on the examples themselves.

Factorising a complicated distribution

A distribution over a whole image or a whole sentence has enormous support, so it cannot be written down as a table. Models get around this by factorising it into a product of simpler conditionals using the chain rule of probability (built from conditional probabilities):

pθ(x1,…,xT)=∏t=1Tpθ(xt∣x1,…,xt−1).p_\theta(x_1, \dots, x_T) = \prod_{t=1}^{T} p_\theta(x_t \mid x_1, \dots, x_{t-1}).

Each factor is a distribution over one token given the ones before it. This is the autoregressive view. A language model is exactly this, and the next-token prediction you train it on is the conditional factor. Other models make different structural choices. Some assume the pixels of an image are conditionally independent given a hidden code, which is the idea behind latent variable models. Others define the distribution through a sequence of noising steps that can be reversed, as in diffusion models.

Sampling

Once trained, drawing a new example is a matter of sampling from the learned distribution. For the autoregressive factorisation this is simple: draw x1x_1 from its conditional, then draw x2x_2 given x1x_1, and so on. Each step is an ordinary draw from a categorical or Gaussian distribution. For latent models the procedure is to draw a hidden code from its prior and then draw the visible example given that code. The quality of the samples depends on how close the model is to the true distribution, and that is where the trade-offs in the next sections come from.

Generative models as classifiers

A generative model can also make predictions about labels. If the data is (x,y)(\mathbf{x}, y) and the model gives p(x∣y)p(\mathbf{x} \mid y) for each class together with a prior p(y)p(y), then Bayes' rule gives the posterior:

p(y∣x)=p(x∣y) p(y)∑y′p(x∣y′) p(y′).p(y \mid \mathbf{x}) = \frac{p(\mathbf{x} \mid y)\, p(y)}{\sum_{y'} p(\mathbf{x} \mid y')\, p(y')}.

This is how naive Bayes classifiers work. The classifier is only as good as the class-conditional models, and a poor model of x\mathbf{x} gives a poor classifier, even if the labels are easy to predict directly.

Worked examples

Example
Fitting a Gaussian generative model by maximum likelihood

Take three training values x1=2x_1 = 2, x2=4x_2 = 4, x3=9x_3 = 9. The model is pθ(x)=N(x;μ,σ2)p_\theta(x) = \mathcal{N}(x; \mu, \sigma^2) with θ=(μ,σ2)\theta = (\mu, \sigma^2).

  1. For a Gaussian, the maximum likelihood estimates are the sample mean and the average squared deviation: μ^=(2+4+9)/3=5\hat\mu = (2 + 4 + 9)/3 = 5.
  2. σ^2=[(2−5)2+(4−5)2+(9−5)2]/3=(9+1+16)/3=26/3≈8.667\hat\sigma^2 = \big[(2-5)^2 + (4-5)^2 + (9-5)^2\big]/3 = (9 + 1 + 16)/3 = 26/3 \approx 8.667. Note that the divisor is nn, not n−1n - 1. The maximum likelihood estimate is biased, and the unbiased version is a different estimator.
  3. The log-likelihood at the estimate is ℓ=−32ln⁡(2πσ^2)−12σ^2∑i(xi−μ^)2=−32(3.9972)−2617.333≈−5.996−1.500=−7.50\ell = -\tfrac{3}{2}\ln(2\pi \hat\sigma^2) - \tfrac{1}{2\hat\sigma^2}\sum_i (x_i - \hat\mu)^2 = -\tfrac{3}{2}(3.9972) - \tfrac{26}{17.333} \approx -5.996 - 1.500 = -7.50.
  4. Compare a poor setting, μ=0\mu = 0 with the same variance. The squared deviations now sum to 4+16+81=1014 + 16 + 81 = 101, giving ℓ=−5.996−101/17.333≈−5.996−5.827=−11.82\ell = -5.996 - 101/17.333 \approx -5.996 - 5.827 = -11.82.
  5. The estimate μ=5\mu = 5 scores about 4.3 nats higher, which is why it is the one we keep. The plot below shows the same comparison as curves over the data.
−202468101200.050.10.15xdensity
  • maximum likelihood: mean 5, σ ≈ 2.94
  • poor choice: mean 0, same σ
The three training points sit on the axis. The fitted curve puts its mass over them; the poor choice centres its mass away from them and scores lower.
Example
Scoring and generating a sentence with a factorised model

A toy language model gives these conditional probabilities. The numbers are made up for illustration.

  • p(the)=0.05p(\text{the}) = 0.05
  • p(cat∣the)=0.02p(\text{cat} \mid \text{the}) = 0.02
  • p(sat∣the cat)=0.30p(\text{sat} \mid \text{the cat}) = 0.30
  1. By the chain rule, p(the cat sat)=0.05×0.02×0.30=0.0003p(\text{the cat sat}) = 0.05 \times 0.02 \times 0.30 = 0.0003.
  2. Reorder the same words as "cat the sat". Suppose p(cat)=0.001p(\text{cat}) = 0.001, p(the∣cat)=0.10p(\text{the} \mid \text{cat}) = 0.10, and p(sat∣cat the)=0.001p(\text{sat} \mid \text{cat the}) = 0.001. Then the probability is 0.001×0.10×0.001=10−70.001 \times 0.10 \times 0.001 = 10^{-7}.
  3. The model rates the first ordering about 3000 times more likely. It has learned word order without being told any grammar rules.
  4. To generate, you would sample the first word from its distribution, then the second from its conditional given the first, and so on. Each run gives a different sentence, but the frequent patterns come out more often.
Example
A generative classifier

Classify a message as spam or not. Suppose the prior is p(spam)=0.4p(\text{spam}) = 0.4 and p(ham)=0.6p(\text{ham}) = 0.6. A generative model of messages gives the likelihood of this particular message as p(x∣spam)=0.02p(\mathbf{x} \mid \text{spam}) = 0.02 and p(x∣ham)=0.005p(\mathbf{x} \mid \text{ham}) = 0.005.

  1. Unnormalised scores: spam 0.02×0.4=0.0080.02 \times 0.4 = 0.008; ham 0.005×0.6=0.0030.005 \times 0.6 = 0.003.
  2. Total: 0.0110.011.
  3. Posterior: p(spam∣x)=0.008/0.011≈0.727p(\text{spam} \mid \mathbf{x}) = 0.008 / 0.011 \approx 0.727.
  4. The message is about 73% likely to be spam. Notice that the prior alone said 40%. The likelihoods moved it up because this message is about four times more typical of spam.

Tradeoffs and failure modes

Generative models are powerful, but the design choice you make sets what they are good at and where they fail.

SituationProblemBetter choice
You only need a labelModeling the full distribution wastes capacity and can hurt accuracy on the boundaryTrain a discriminative classifier directly
You need exact likelihoods and samplingMany architectures cannot normalise the density, so the likelihood is intractableAutoregressive models, flows, or models with tractable normalisation
You want fast, sharp samplesSome likelihood-based models produce blurry or slow samplesGANs for speed, diffusion models for quality
Data has several modesSimple models collapse onto one mode and drop the restMixtures, latent variable models, or models with richer hidden structure
The model must sample from a discrete spaceGradients do not pass through discrete drawsReparameterised relaxations, or autoregressive training

Some practical warnings:

  • Likelihood is not the same as quality. A model can assign high likelihood to bland, averaged outputs while producing poor-looking samples, or the reverse. Always inspect samples as well as the training loss.
  • Memorisation looks like good fit. A high-capacity model can push probability onto its training examples exactly. Held-out likelihood is the check.
  • Generative training spends effort on details you may not need. To assign a probability to every pixel, the model must model fine texture, which a classifier never has to do.
  • Density values are not probabilities of events. For continuous data, p(x)p(\mathbf{x}) can exceed 1. Compare densities only across models that use the same units.

History

Early generative ideas came from statistics in the late 1800s. Karl Pearson fitted mixtures of normal curves to data in 1894, which was an early density model with several components. Ronald Fisher's work on maximum likelihood in the 1920s gave the training rule that most later models still use.

Naive Bayes classifiers, which are generative models with a conditional independence assumption, became common in the 1950s and 1960s for text and spam-like tasks. They worked well for their size and showed the benefit of modeling how the data was produced.

The modern wave started with neural density models. Restricted Boltzmann machines and deep belief networks, pushed by Geoffrey Hinton and colleagues in the mid-2000s, showed that deep networks could be pretrained as generative models. Variational autoencoders (2013) and generative adversarial networks (2014) then made large-scale generation practical. Autoregressive language models and diffusion models carried the idea to text and images in the following years. Those systems are generative models in the sense used here, even when their architectures look very different.

Check yourself

QuestionA model assigns probability 0.0001 to one sentence and 0.00002 to another. Which does it consider more plausible, and by what factor?Show answer

The first, by a factor of 5. Probabilities are compared by ratio, so 0.0001/0.00002=50.0001 / 0.00002 = 5. Because the model is a distribution over sentences, this comparison says which sentence it thinks is more typical of its training data.

QuestionWhat is the loss a generative model minimises during standard training, and why is it the same as maximising likelihood?Show answer

The average negative log-likelihood, −1n∑ilog⁡pθ(xi)-\frac{1}{n}\sum_i \log p_\theta(\mathbf{x}_i). The logarithm is monotonic, so maximising the sum of log-probabilities over the data is the same as maximising the probability of the data. Negating turns the maximisation into a minimisation, and the result is the cross-entropy between the data distribution and the model.

QuestionYou want a model that answers whether an email is spam, and you have a generative model of emails. Why might a discriminative classifier still beat it on accuracy, and when could the generative model still be worth having?Show answer

A discriminative model spends all its capacity on the boundary between spam and ham, which is the only thing the task needs. A generative model also spends capacity on modeling every detail of email text, and any error there can hurt the classification. The generative model is still worth having when you also want to detect unusual emails, generate examples, or handle a new class without labelled data.

QuestionA language model assigns probability 10−1210^{-12} to a 20-token sentence. Why is it still a sensible way to measure quality, and what would you compare it with?Show answer

The probability of any one specific long sentence is tiny, because there are huge numbers of possible sentences. The sensible measure is the log-probability per token, or the perplexity, which normalises for length. Comparing two models on the same held-out text, the one with lower average negative log-probability per token is the better model of that text.

Sources