Skip to main content
LearnMLAcademy
Advanced10 min read

How Generative Models Learn and Generate New Data

Understand how generative models estimate and sample distributions, with diffusion diagrams, prompt experiments, and output-quality checks.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

How can a model create something it has never stored?

A generative model studies many examples and adjusts its internal parameters so that common structures become more likely than implausible ones. During generation, it uses those learned patterns plus a starting signal—often a random value, a prompt, a class label, an image, or an unfinished sequence—to construct a new sample.

By the end of this lesson, you will be able to explain what a learned data distribution means, what a latent representation stores, why randomness creates variety, how conditioning gives control, and why training and generation are separate processes.

How Generative Models Learn in Simple Words

Imagine a master musician who has listened to thousands of jazz songs. They haven’t memorized every note by rote; instead, they have learned the probability space of jazz—which chord progressions usually follow one another, where surprises sound pleasant, and how tempo shapes emotion. When given a theme (condition) and a burst of spontaneous improvisation (random seed), they compose a fresh, original solo!

1

Learn Distribution

Map which features occur together

2

Compact Latent Space

Organize concepts into hidden coordinates

3

Sample with Seed

Randomness converts odds into a unique draft

4

Guide with Condition

Prompts steer probability towards user intent

Figure 1 — Learning mode builds the model; generation mode reuses it

Training measures an error and sends a parameter update back to the learned representation. Generation starts from a condition plus sampled randomness and reuses the same trained model without updating it.

The training lane sends a dataset into a learned representation or distribution, produces a reconstruction, measures loss, and feeds a parameter update back into the model. A dotted bridge leads to the generation lane, where a condition and sampled latent value or noise enter the same trained model with fixed parameters to produce a new sample.

Two different questions: deciding and generating

Suppose a dataset contains photographs of forests, coasts, and cities. A discriminative model receives one photograph and asks which class it belongs to. A generative model asks what combinations of colour, texture, shape, and layout would look plausible among those photographs.

Model viewpointQuestionInputOutput
Discriminative“Which class does this example belong to?”An existing photographForest, coast, or city
Generative“What examples could plausibly come from this data?”A starting signal and optional guidanceA newly constructed scene

What “learning the data distribution” means

A distribution describes which outcomes are possible and how likely they are. For a simple dataset, it may say that 5 of 10 scenes are forests, 3 are coasts, and 2 are cities. A useful image model must learn much richer relationships: where sky usually appears, how water reflects light, which edges form buildings, and which combinations rarely occur.

Tiny probability estimate

p̂(category) = count(category) / N

Here count(category) comes from the training data and N = 10 is the total number of examples. Therefore p̂(forest) = 5/10 = 0.50, p̂(coast) = 3/10 = 0.30, and p̂(city) = 2/10 = 0.20. The hat on p̂ means this is an estimate learned from available data, not a perfect description of the real world.

Representation and latent-space intuition

A representation is an internal numerical description that preserves useful features. A latent space is a representation space whose coordinates are learned rather than directly supplied as labels. One direction might respond to open water, another to brightness, and another to dense vertical edges—even when nobody named those features during training.

“Latent” means hidden. A point in latent space is not the address of a saved picture. It is a compact set of feature values that a decoder or generator can transform into an output. Nearby points often produce related outputs because their feature values are similar.

Figure 2 — A latent space stores useful relationships, not file locations

Nearby points represent examples with similar learned features. A sampled point between known examples can decode into a related new example.

A two-dimensional latent space contains nearby green forest examples, blue coast examples, and amber city examples. Horizontal movement means more water-like and vertical movement means brighter or more open. A sampled latent point z near the coast cluster follows a curved decoding arrow to a newly constructed coast scene.

Randomness, sampling, and conditioning

Randomness supplies variety

A random number, noise vector, or random token choice lets repeated runs reach different plausible regions instead of returning one fixed result.

Sampling makes a choice

Sampling uses the learned probabilities to select a next token, latent point, category, or denoising path.

Conditioning supplies direction

A prompt, class, reference image, mask, or other signal changes which outputs are likely without removing all variety.

Worked example: one random value, two distributions

ValueValue usedWhere it came fromRole
Unconditional probabilitiesforest 0.50, coast 0.30, city 0.20Calculated from 10 training examplesBase learned distribution
ConditionsunsetChosen by the developer or userGuides the requested output
Conditional probabilitiesforest 0.20, coast 0.70, city 0.10Toy values representing learned sunset relationshipsDistribution after guidance
Random draw r0.35Normally produced by a random-number generatorSelects one probability interval

Without a condition

Intervals: forest [0.00, 0.50), coast [0.50, 0.80), city [0.80, 1.00).

Because 0.35 lies in [0.00, 0.50), the calculated choice is forest.

Conditioned on “sunset”

Intervals: forest [0.00, 0.20), coast [0.20, 0.90), city [0.90, 1.00).

The same 0.35 now lies in [0.20, 0.90), so the calculated choice becomes coast.

Reproduce the sampling calculation in Python

The function adds probabilities from left to right. The first cumulative interval containing random_value determines the result.

Python 3
categories = ["forest", "coast", "city"]

# Calculated from 10 training examples: 5 forest, 3 coast, 2 city
unconditional = [0.50, 0.30, 0.20]

# Learned for the developer-supplied condition "sunset"
sunset_condition = [0.20, 0.70, 0.10]

def choose_category(random_value, probabilities):
    running_total = 0.0
    for category, probability in zip(categories, probabilities):
        running_total += probability
        if random_value < running_total:
            return category

r = 0.35  # normally supplied by a random-number generator
print("Unconditional sample:", choose_category(r, unconditional))     # forest
print("Sunset condition sample:", choose_category(r, sunset_condition))  # coast

Interactive Sampling & Conditioning Simulator

Drag the random value slider r in [0, 1) or switch conditions to see how samples emerge!

Condition:
Random Uniform Sample: r = 0.42
Forest (50%)
Coast (30%)
City (20%)
0.42
Generated Candidate Output
ForestInterval: [0.00, 0.50)

The random seed 0.42 landed in the Forest cumulative interval. Changing condition shifts interval widths without retraining the weights!

What can go wrong?

The data distribution is incomplete

A model trained mostly on daylight photographs will not automatically learn reliable night scenes.

Likelihood is not truth

A plausible sentence or image can still contain a factual, physical, or social error.

Conditioning is influence, not a guarantee

A prompt can guide the distribution without forcing every detail to appear correctly.

Novel-looking output may still be too similar

Duplicates, small datasets, and overfitting can cause memorization or privacy leakage.

Summary / Key Takeaways

  • A generative model learns patterns that make some data examples more plausible than others.
  • A discriminative model labels an existing example; a generative model can construct a new one.
  • A representation stores useful numerical features, and a latent space is a learned hidden representation space.
  • Sampling turns learned probabilities into one concrete choice; randomness allows multiple valid outputs.
  • Conditioning changes the output distribution using a prompt, class, image, or other guiding signal.
  • Training updates parameters from examples and an objective; generation reuses fixed trained parameters.
  • Autoregressive, VAE, GAN, and diffusion models reach new samples through different mechanisms covered in later lessons.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "How Generative Models Learn and Generate New Data"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5
What does it mean for a generative model to learn a data distribution?
Question 2 of 5
A model assigns probabilities forest = 0.50, coast = 0.30, and city = 0.20. Which category is selected by random value r = 0.72?
Question 3 of 5
What is the main purpose of conditioning during generation?
Question 4 of 5
Which statement correctly distinguishes training from generation?
Question 5 of 5
A system must create text one token at a time, using each chosen token to help choose the next. Which high-level mechanism fits best?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What does it mean for a generative model to learn a data distribution?▼

Correct Answer: It learns which features and combinations are more or less plausible in the training data

A learned distribution represents patterns and relative likelihoods. It can guide a new sample, but it is neither a file store nor a guarantee of truth.

2A model assigns probabilities forest = 0.50, coast = 0.30, and city = 0.20. Which category is selected by random value r = 0.72?▼

Correct Answer: Coast

The cumulative intervals are forest [0.00, 0.50), coast [0.50, 0.80), and city [0.80, 1.00). Since 0.72 lies in the coast interval, coast is selected.

3What is the main purpose of conditioning during generation?▼

Correct Answer: To guide the likely outputs using information such as a prompt, class, image, or mask

Conditioning changes which outputs are likely. It guides generation while still allowing variation, and it does not normally update the trained parameters.

4Which statement correctly distinguishes training from generation?▼

Correct Answer: Training updates parameters using examples and an objective; generation uses trained parameters to create a sample

Training is the learning phase in which parameters change. Generation, also called inference, normally keeps those parameters fixed and uses a starting signal to produce an output.

5A system must create text one token at a time, using each chosen token to help choose the next. Which high-level mechanism fits best?▼

Correct Answer: Autoregressive generation

Autoregressive generation builds a sequence step by step, conditioning each new part on the parts already produced. Later LLM lessons explain the method in detail.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next