Lesson 8 of 12 · Core Algorithms
Probabilistic Models
Probabilistic models explained: Bayes' rule, Naive Bayes for text and numbers, generative vs discriminative models, and checking that probabilities are honest.
- 13 min read
- Intermediate
- Reviewed
- Explain what makes a model probabilistic, and why honest probabilities are useful
- Apply Bayes' rule and the naive independence assumption by hand
- Build Naive Bayes classifiers for text and for numbers in scikit-learn
- Tell generative models (Naive Bayes) from discriminative ones (logistic regression)
- Check whether probabilities are calibrated, and use them to make decisions
The idea in plain words
Any classifier can pick a class. A probabilistic model also says how sure it is, and that number should mean what it says: of all the emails it gives a spam probability of 0.8, about 80% should really be spam. Honest probabilities let you rank cases, set thresholds and weigh costs, as later lessons do.
There are two broad ways to build one:
Bayes' rule, one clue at a time
Bayes' rule turns "how often does this clue appear in spam?" into "how likely is spam, given this clue?":
P(class | clues) ∝ P(class) × P(clues | class)
∝ means "is proportional to": work out this product for every class,
then divide each product by their total, so the probabilities add up to 1.The naive part is an assumption that makes the second factor easy: within each class, treat every clue as independent of the others, so the probability of several clues is just the product of their separate probabilities.
# What we know from past emails
p_spam = 0.3 # 30% of all emails are spam
p_word_given = { # how often each word appears...
"free": {"spam": 0.60, "not": 0.05}, # ...in spam and in normal emails
"meeting": {"spam": 0.10, "not": 0.40},
}
def p_spam_given(words):
spam, normal = p_spam, 1 - p_spam # start from how common each class is
for w in words: # "naive": multiply the clues together
spam *= p_word_given[w]["spam"]
normal *= p_word_given[w]["not"]
return spam / (spam + normal) # Bayes' rule: scale so they add up to 1
print(f"P(spam | 'free') = {p_spam_given(['free']):.3f}")
print(f"P(spam | 'meeting') = {p_spam_given(['meeting']):.3f}")
print(f"P(spam | 'free', 'meeting') = {p_spam_given(['free', 'meeting']):.3f}")P(spam | 'free') = 0.837 P(spam | 'meeting') = 0.097 P(spam | 'free', 'meeting') = 0.562
Before reading anything, the chance of spam is 0.3. The word "free" is 12 times more common in spam (0.60 against 0.05), so it lifts the probability to 0.837. "meeting" points the other way and drops it to 0.097. With both words, the two clues pull against each other and the result is 0.562. Training a Naive Bayes model means nothing more than estimating these numbers by counting, which is why it is so fast.
Naive Bayes for text
CountVectorizer turns each message into word counts, and MultinomialNB learns how often each word appears in each class. Here are 12 made-up messages:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
messages = [
"win a free prize now", "free money claim your prize", "urgent claim free cash now",
"you won a free holiday", "cheap loans call now", "claim your cash reward today",
"meeting moved to monday", "can you send the report", "lunch at noon tomorrow",
"the report is ready for review", "see you at the meeting", "call me when you are free",
]
labels = ["spam"] * 6 + ["normal"] * 6
model = make_pipeline(CountVectorizer(), MultinomialNB())
model.fit(messages, labels)
new = ["free cash prize", "report for the monday meeting", "are you free for lunch"]
for text, probs in zip(new, model.predict_proba(new)):
print(f"{text:<30} P(normal)={probs[0]:.2f} P(spam)={probs[1]:.2f}")
print("classes:", model.classes_.tolist())free cash prize P(normal)=0.04 P(spam)=0.96 report for the monday meeting P(normal)=0.99 P(spam)=0.01 are you free for lunch P(normal)=0.84 P(spam)=0.16 classes: ['normal', 'spam']
"free cash prize" is 96% spam. "are you free for lunch" contains "free" too, but "you", "for" and "lunch" all point to normal messages, so the model calls it normal (0.84). Words never seen in a class don't make its probability zero, because MultinomialNB adds a small count to every word (smoothing, set by alpha=1.0 by default).
The last line matters: the columns of predict_proba follow model.classes_, which scikit-learn sorts alphabetically, so column 0 is "normal" and column 1 is "spam". With so little training data, a Naive Bayes text classifier is often a strong, cheap first model.
Naive Bayes for numbers
For measurements, GaussianNB assumes each feature follows a bell curve (a normal distribution) within each class, and learns each curve's average and spread. On the wine data from Instance-Based Models:
from sklearn.datasets import load_wine
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import cross_val_score
X, y = load_wine(return_X_y=True)
model = GaussianNB().fit(X, y)
# For each class, Gaussian Naive Bayes stores the average and spread of every feature
print("average alcohol per grower:", model.theta_[:, 0].round(2))
print("variance of alcohol per grower:", model.var_[:, 0].round(2))
print("class shares learned from the data:", model.class_prior_.round(2))
print(f"5-fold accuracy: {cross_val_score(GaussianNB(), X, y, cv=5).mean():.2f}")average alcohol per grower: [13.74 12.28 13.15] variance of alcohol per grower: [0.21 0.29 0.28] class shares learned from the data: [0.33 0.4 0.27] 5-fold accuracy: 0.97
The model has learned, for example, that the second grower's wines average 12.28% alcohol while the first grower's average 13.74%, and it stores the same kind of summary for all 13 features. That's the entire model, yet it scores 0.97 with no scaling and no tuning.
| Variant | For features that are | Example |
|---|---|---|
MultinomialNB | Counts | How often each word appears |
BernoulliNB | Yes/no | Whether each word appears at all |
GaussianNB | Continuous measurements | Chemical measurements, sensor readings |
CategoricalNB | Categories | Colour, country, device type |
The Naive Bayes course covers each variant in depth.
Are the probabilities honest?
The naive assumption can make probabilities far too confident. In the data below, there is only one real clue, but it was copied, with a little noise, into five features. The program compares predicted probabilities with what really happened, grouping the test cases into five bins:
import numpy as np
from sklearn.calibration import CalibratedClassifierCV, calibration_curve
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss
from sklearn.naive_bayes import GaussianNB
rng = np.random.RandomState(0)
def make_data(n):
y = rng.randint(0, 2, size=n)
signal = rng.normal(loc=y * 1.5, scale=1.0) # one real clue
copies = [signal + rng.normal(0, 0.1, size=n) for _ in range(5)]
return np.column_stack(copies), y # 5 near-copies of it
X_train, y_train = make_data(2000)
X_test, y_test = make_data(2000)
for model in [GaussianNB(), LogisticRegression()]:
p = model.fit(X_train, y_train).predict_proba(X_test)[:, 1]
observed, predicted = calibration_curve(y_test, p, n_bins=5, strategy="quantile")
print(f"{type(model).__name__} (Brier score {brier_score_loss(y_test, p):.3f})")
for pred, obs in zip(predicted, observed):
print(f" says {pred:.2f} on average -> really class 1: {obs:.2f}")
fixed = CalibratedClassifierCV(GaussianNB(), cv=5).fit(X_train, y_train)
p = fixed.predict_proba(X_test)[:, 1]
print(f"GaussianNB after CalibratedClassifierCV: Brier score {brier_score_loss(y_test, p):.3f}")GaussianNB (Brier score 0.193) says 0.00 on average -> really class 1: 0.09 says 0.02 on average -> really class 1: 0.26 says 0.57 on average -> really class 1: 0.50 says 0.99 on average -> really class 1: 0.72 says 1.00 on average -> really class 1: 0.93 LogisticRegression (Brier score 0.157) says 0.08 on average -> really class 1: 0.09 says 0.28 on average -> really class 1: 0.26 says 0.52 on average -> really class 1: 0.50 says 0.76 on average -> really class 1: 0.72 says 0.93 on average -> really class 1: 0.93 GaussianNB after CalibratedClassifierCV: Brier score 0.166
Naive Bayes treats the five copies as five independent pieces of evidence and multiplies them, so it counts the same clue five times and becomes far too sure of itself. When it says 0.99, only 72% of those cases are really class 1; when it says 0.02, 26% are. Logistic regression learns its weights together, so it effectively counts the clue once, and its probabilities match reality closely (it says 0.76 and 72% are; it says 0.93 and 93% are). Its Brier score is lower too: 0.157 against 0.193.
CalibratedClassifierCV repairs a model's probabilities by learning a correction on held-out folds, which brings Naive Bayes down to 0.166. Note that an overconfident model can still rank cases well; it's the numbers themselves you can't take at face value.
Using probabilities to decide
Calibrated probabilities let you weigh costs directly. Suppose checking a payment by hand costs 5, and catching a fraudulent payment saves 200. Checking is worth it whenever the expected saving beats the cost:
check a payment when P(fraud) × 200 > 5
which means P(fraud) > 5 ÷ 200 = 0.025So the right threshold here is 2.5%, not the default 50%, and it only works if a predicted 2.5% really means 2.5%. The project at the end of this course uses the same reasoning to decide which customers get a retention offer.
Common mistakes
Practice
Classify a review that contains both great and refund, with Naive Bayes by hand.
# A review classifier learned these numbers from past reviews
p_positive = 0.6 # 60% of reviews are positive
p_word = {
"great": {"positive": 0.50, "negative": 0.10},
"refund": {"positive": 0.05, "negative": 0.30},
}
review_words = ["great", "refund"]
# Naive Bayes: for each class, multiply the class share by P(word | class)
# for every word in the review. Then divide the positive score by the
# sum of both scores. Print with three decimals, for example:
# P(positive | great, refund) = 0.500
positive_score = p_positive
negative_score = 1 - p_positive
print(f"P(positive | great, refund) = {positive_score:.3f}")
Why are Naive Bayes probabilities often too extreme (too close to 0 or 1)?
Summary
- A probabilistic model gives a probability for each class, and those probabilities should be calibrated: 0.8 should come true about 80% of the time.
- Generative models such as Naive Bayes learn what each class looks like and apply Bayes' rule; discriminative models such as logistic regression learn the class probabilities directly.
- Naive Bayes multiplies the evidence from each feature, assuming independence. It trains by counting, so it is very fast and works well for text (
MultinomialNB) and simple measurements (GaussianNB). - Related features make Naive Bayes overconfident; check with
calibration_curveand the Brier score, and fix withCalibratedClassifierCV. - Calibrated probabilities turn into decisions by comparing expected benefit with cost.
Next: Choosing an Algorithm, putting the four families side by side.
Finished reading? Tick it off to track your progress.