Lesson 9.1 · 1 of 5 · 5 min read · Reviewed 24 Nov 2026
Discriminative vs generative models
By the end, you can
- Tell a discriminative model from a generative one by what it learns.
- Decide when a small classifier beats calling an LLM.
Machine learning models fall into two broad families, and knowing which one you are holding tells you what it can and can’t do.
Two questions a model can learn to answer
A discriminative model learns “given this input, which label?”. In probability terms it learns p(label | input). A spam filter that reads an email and returns spam: 0.97 is discriminative. It never learns what emails look like in general; it only learns where the line between spam and not-spam falls.
A generative model learns “what does the data itself look like?”: p(input), or p(input, label). Because it has a model of the data, it can sample new examples. A language model is generative: it learns p(next tokenToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. | the tokens so far), and chaining those predictions gives a probability for, and a way to write, whole passages.
| Discriminative | Generative | |
|---|---|---|
| Learns | p(label given input) | p(data), often one piece at a time |
| Output | A score or label from a fixed set | New text, images or audio |
| Classic examples | Logistic regression, a fine-tuned BERT classifier | Naive Bayes, LLMs, diffusion image models |
| Typical size and cost | Small, cheap, fast | Often large; cost grows with output length |
A worked example: one email, two models
Take the email “Win a free cruise, reply now”.
- A logistic regression spam filter turns it into features (the words win, free, now), weighs them and outputs
0.97 spam. It cannot say anything else. - An LLMLarge language model (LLM): A neural network trained on large amounts of text to predict the next token, which lets it generate and transform language. given the prompt
Email: Win a free cruise, reply now. Label (spam or ok):continues the text. The most likely next token isspam. You have used a generative model as a classifier by making the label the thing it writes.
The second approach needs no labelled data, which is why it is so convenient. But it has costs: each call runs a large model, and nothing stops it writing Spam!, junk or a polite paragraph instead of one of your labels. You fix that with clear instructions, structured outputsStructured outputs: Making a model return data that matches a defined schema, such as JSON with required fields and types. or constrained decoding, and you still need an evalEval: A repeatable test that measures how well an AI system performs on a set of cases with defined success criteria..
Why builders should care
Many “LLM projects” are really classification: route a ticket, flag a risky message, detect a language. A useful pattern is:
- Prototype with an LLM, because it works with zero labelled data.
- Collect its outputs and correct them, building a labelled set.
- Train a small discriminative model (or a classifier on top of embeddingsEmbedding: A list of numbers (a vector) that represents the meaning of a piece of text, so similar meanings land close together., chapter 4) once volume is high and the labels are stable.
The LLM stays for the open-ended work: drafting the reply, explaining the decision, handling the odd case the classifier is unsure about.
Common mistakes
- Treating an LLM’s label as a calibrated probability. A generated “spam” is not the same as a score of 0.97. If you need thresholds, use a classifier’s scores or measure accuracy per label.
- Using a giant model for a six-label task at huge volume when a small classifier would be faster, cheaper and easier to audit.
- Forgetting the label set. A generative model can drift outside it. Validate every output against the allowed values.
Key points
- A discriminative model learns the chance of a label given an input: it draws a boundary between classes.
- A generative model learns the chance of the data itself, so it can produce new examples; an LLM does this one token at a time.
- You can use a generative model as a classifier by asking it to write the label, but it may write a label you never offered.
- For a fixed label set at high volume, a small discriminative classifier is often cheaper, faster and easier to test.
Train a classifier and a generator side by side
Train a discriminative and a generative model on the same tiny spam set and see what each can do.
You will have: A script that prints both models' test accuracy and the words the generative model thinks typify each class.
Steps
- Read the training set and the logistic regression, which learns p(spam given words) directly.
- Fill in nb_log_prob: the naive Bayes score of a text under one class, with add-one smoothing.
- Fill in nb_typical_words so the generative model can describe what spam looks like.
- Run it and compare: both classify, but only one can say what a class looks like.
- Add a test message of your own and see whether the two models agree.
Done when
- Both models score 4/4 on the test messages.
- The typical spam words include free and now.
- You can say which model could be used to sample new spam-like text, and why.
Open in the Playground No API key needed.
Starter code (Python)
import math
# Tiny labelled set: 1 = spam, 0 = ok.
TRAIN = [
("win a free cruise now", 1), ("claim your free prize today", 1),
("cheap loans win cash now", 1), ("free gift card claim now", 1),
("meeting moved to friday", 0), ("can you review my draft today", 0),
("lunch on friday with the team", 0), ("draft notes from the meeting", 0),
]
TEST = [("free cash prize now", 1), ("team meeting notes", 0), ("claim a free cruise", 1), ("review the friday draft", 0)]
VOCAB = sorted({w for text, _ in TRAIN for w in text.split()})
# Discriminative: logistic regression learns p(spam | words) directly.
def features(text):
words = set(text.split())
return [1.0 if w in words else 0.0 for w in VOCAB]
def train_logreg(epochs=200, lr=0.5):
w, b = [0.0] * len(VOCAB), 0.0
for _ in range(epochs):
for text, y in TRAIN:
x = features(text)
p = 1 / (1 + math.exp(-(sum(wi * xi for wi, xi in zip(w, x)) + b)))
d = p - y
w = [wi - lr * d * xi for wi, xi in zip(w, x)]
b -= lr * d
return w, b
def logreg_prob(model, text):
w, b = model
return 1 / (1 + math.exp(-(sum(wi * xi for wi, xi in zip(w, features(text))) + b)))
# Generative: naive Bayes learns how each class writes, p(words | class).
def train_nb():
counts = {0: {}, 1: {}}
for text, y in TRAIN:
for word in text.split():
counts[y][word] = counts[y].get(word, 0) + 1
return counts
def nb_log_prob(counts, text, label):
# TODO: return the sum over words of log((count of word in this class + 1) / (total words in class + len(VOCAB)))
return 0.0
def nb_classify(counts, text):
return 1 if nb_log_prob(counts, text, 1) > nb_log_prob(counts, text, 0) else 0
def nb_typical_words(counts, label, k=4):
# TODO: return the k most frequent words for this class (ties in alphabetical order).
# Because it models the data, the generative model can describe what a class looks like.
return []
lr_model, nb_model = train_logreg(), train_nb()
lr_right = sum((logreg_prob(lr_model, t) > 0.5) == bool(y) for t, y in TEST)
nb_right = sum(nb_classify(nb_model, t) == y for t, y in TEST)
print(f"Logistic regression accuracy: {lr_right}/{len(TEST)}")
print(f"Naive Bayes accuracy: {nb_right}/{len(TEST)}")
print(f"p(spam | 'free cash prize now') = {logreg_prob(lr_model, 'free cash prize now'):.2f}")
print("Typical spam words:", ", ".join(nb_typical_words(nb_model, 1)))
print("Typical ok words:", ", ".join(nb_typical_words(nb_model, 0)))
Show a solution
import math
# Tiny labelled set: 1 = spam, 0 = ok.
TRAIN = [
("win a free cruise now", 1), ("claim your free prize today", 1),
("cheap loans win cash now", 1), ("free gift card claim now", 1),
("meeting moved to friday", 0), ("can you review my draft today", 0),
("lunch on friday with the team", 0), ("draft notes from the meeting", 0),
]
TEST = [("free cash prize now", 1), ("team meeting notes", 0), ("claim a free cruise", 1), ("review the friday draft", 0)]
VOCAB = sorted({w for text, _ in TRAIN for w in text.split()})
# Discriminative: logistic regression learns p(spam | words) directly.
def features(text):
words = set(text.split())
return [1.0 if w in words else 0.0 for w in VOCAB]
def train_logreg(epochs=200, lr=0.5):
w, b = [0.0] * len(VOCAB), 0.0
for _ in range(epochs):
for text, y in TRAIN:
x = features(text)
p = 1 / (1 + math.exp(-(sum(wi * xi for wi, xi in zip(w, x)) + b)))
d = p - y
w = [wi - lr * d * xi for wi, xi in zip(w, x)]
b -= lr * d
return w, b
def logreg_prob(model, text):
w, b = model
return 1 / (1 + math.exp(-(sum(wi * xi for wi, xi in zip(w, features(text))) + b)))
# Generative: naive Bayes learns how each class writes, p(words | class).
def train_nb():
counts = {0: {}, 1: {}}
for text, y in TRAIN:
for word in text.split():
counts[y][word] = counts[y].get(word, 0) + 1
return counts
def nb_log_prob(counts, text, label):
total = sum(counts[label].values())
return sum(math.log((counts[label].get(w, 0) + 1) / (total + len(VOCAB))) for w in text.split())
def nb_classify(counts, text):
return 1 if nb_log_prob(counts, text, 1) > nb_log_prob(counts, text, 0) else 0
def nb_typical_words(counts, label, k=4):
# Because it models the data, the generative model can describe what a class looks like.
return [w for w, _ in sorted(counts[label].items(), key=lambda kv: (-kv[1], kv[0]))[:k]]
lr_model, nb_model = train_logreg(), train_nb()
lr_right = sum((logreg_prob(lr_model, t) > 0.5) == bool(y) for t, y in TEST)
nb_right = sum(nb_classify(nb_model, t) == y for t, y in TEST)
print(f"Logistic regression accuracy: {lr_right}/{len(TEST)}")
print(f"Naive Bayes accuracy: {nb_right}/{len(TEST)}")
print(f"p(spam | 'free cash prize now') = {logreg_prob(lr_model, 'free cash prize now'):.2f}")
print("Typical spam words:", ", ".join(nb_typical_words(nb_model, 1)))
print("Typical ok words:", ", ".join(nb_typical_words(nb_model, 0)))