Learning path: Choose and Tune a Model: Classic Algorithms to a Saved Pipeline · Step 2 of 10
Naive Bayes: Prior Times Likelihood, a Spam Filter by Hand and GaussianNB
Build a four-word spam filter by hand: prior 0.56 vs 0.44, a spam score of exactly zero, Laplace smoothing to fix it and logs so tiny numbers don't vanish. Then GaussianNB scores 0.967 on iris.
What you will learn
- Explain prior, likelihood and posterior with a doctor's diagnosis
- Score a message for spam by hand from word counts
- Fix the zero problem with Laplace smoothing (alpha = 1) and add logs instead of multiplying
- Choose Multinomial NB for counts and Gaussian NB for measurements, and fit GaussianNB on iris
Before you start
- Basic pandas
- Train-Test Split and Data Leakage
Think about a doctor. Before looking at you, the doctor already has a first guess: how common is the flu this week? Maybe 10%. You say you have a fever, and the belief goes up to 40%. You also have a cough: now it's 75%.
First guess, updated by every clue. That's Bayes' theorem, and it's the whole idea behind Naive Bayes. We'll build a tiny spam filter by hand, then use scikit-learn on flowers.
Three names, one idea
prior x likelihood = posterior (up to a constant that is the same for every class).
- Prior: the first guess. How common is spam before you read the message?
- Likelihood: how typical the clues are inside each class. How typical are these words in spam?
- Posterior: the updated belief after reading the message.
You score every class the same way, and the biggest score wins.
Count the words, find the prior
Our data is a tiny table of word counts from 10 normal messages and 8 spam messages:
import numpy as np
import pandas as pd
words = pd.read_csv("spam_words.csv", index_col="word")
words
normal spam
word
money 3 6
free 2 7
tonight 3 0
party 5 2
"free" shows up 2 times in normal messages and 7 times in spam. The prior is just the share of each class among the 18 messages:
prior = {"normal": 10 / 18, "spam": 8 / 18}
print({k: round(v, 2) for k, v in prior.items()})
{'normal': 0.56, 'spam': 0.44}
The likelihood of each word
Divide every count by its column total, and you get how often each word appears inside each class:
likelihood = words / words.sum()
likelihood.round(2)
normal spam
word
money 0.23 0.40
free 0.15 0.47
tonight 0.23 0.00
party 0.38 0.13
Score "free tonight"
A message arrives: "free tonight". For each class, multiply the prior by the likelihood of every word in the message:
msg = ["free", "tonight"]
for c in ["normal", "spam"]:
like = likelihood.loc[msg, c].prod()
print(c, round(prior[c] * like, 4))
normal 0.0197
spam 0.0
Two things to notice.
First, we simply multiply the word likelihoods, as if each word ignored the others. In real messages, words do go together. That shortcut is the naive part, and it works surprisingly well.
Second, the spam score is exactly zero, because "tonight" never showed up in spam. One zero wipes out the whole score, no matter how spammy the other words are.
Fix the zero: add 1 to every count (alpha)
Add 1 to every count before dividing, so no word is ever zero. This 1 is called alpha, and the trick is Laplace smoothing.
smooth = (words + 1) / (words + 1).sum()
for c in ["normal", "spam"]:
like = smooth.loc[msg, c].prod()
print(c, round(prior[c] * like, 4))
normal 0.0231
spam 0.0098
The spam score isn't zero any more. Normal is still bigger, so "free tonight" is a normal message.
Add logs, don't multiply
One more practical problem. A long email has hundreds of words, each with a small likelihood. Multiply 400 numbers of 0.01 together and see what happens:
p = np.full(400, 0.01)
print("multiply:", np.prod(p))
print("add logs:", round(np.log(p).sum(), 1))
multiply: 0.0
add logs: -1842.1
The product is so tiny that the computer rounds it to 0.0, and every class would score the same. Adding the logs gives -1842.1, a perfectly normal number. Because the log keeps the order of the scores, the winning class stays the same. So Naive Bayes in practice adds logs instead of multiplying tiny numbers.
Multinomial for counts, Gaussian for measurements
- Multinomial NB (
MultinomialNB) works with counts, such as how many times each word appears. That's our spam filter. - Gaussian NB (
GaussianNB) works with measurements, such as the petal length of a flower. Each class gets its own bell curve per column, and the likelihood is the height of that curve at the new value.
GaussianNB on the iris flowers
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
X, y = load_iris(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
nb = GaussianNB().fit(X_train, y_train)
acc = nb.score(X_test, y_test)
print("test accuracy:", round(acc, 3))
print(nb.predict_proba(X_test.iloc[[0]]).round(3))
print(nb.predict(X_test.iloc[[0]]))
test accuracy: 0.967
[[1. 0. 0.]]
[0]
0.967 on the test set: 29 of 30 flowers right. The first test flower gets probabilities 1, 0 and 0, so it's class 0, setosa.
What did the model learn? For every class and column, a mean and a spread. Here are the bell curves for petal length:
col = list(X.columns).index("petal length (cm)")
print("means:", nb.theta_[:, col].round(2))
print("std: ", np.sqrt(nb.var_[:, col]).round(2))
print(X_test.iloc[0]["petal length (cm)"])
means: [1.48 4.25 5.58]
std: [0.16 0.44 0.57]
1.3
The new flower's petal length is 1.3, right under the setosa curve centred at 1.48. That curve is highest at 1.3, so setosa wins.
Common mistakes
- Forgetting smoothing. One word never seen in a class sends that class to zero. scikit-learn's
MultinomialNBusesalpha=1.0by default. - Multiplying hundreds of probabilities. Add logs instead.
- The wrong flavour. Counts go to Multinomial, measurements go to Gaussian.
- Ignoring the prior. The first guess matters: a rare class needs strong clues to win.
Quick recap
| Idea | What it means | In this example |
|---|---|---|
| Prior | How common each class is | normal 0.56, spam 0.44 |
| Likelihood | How typical each clue is in a class | "free": 0.15 normal, 0.47 spam |
| Naive | Multiply the clues as if independent | prior x free x tonight |
| Laplace, alpha = 1 | Add 1 to every count | spam 0.0 becomes 0.0098 |
| Logs | Add logs instead of multiplying | 0.0 becomes -1842.1 |
| GaussianNB | One bell curve per class and column | iris test accuracy 0.967 |
Try it yourself
Score the message "money party" by hand with alpha = 1. Is it spam or normal?
Next: a model that draws the widest road between two groups, Support Vector Machines. Before this one: K-Nearest Neighbours.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →K-Nearest Neighbours (KNN): Distance, k and Why Scaling Is a Must
Next →Support Vector Machines (SVM): The Widest Road, C, Kernels and gamma
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Linear Regression and the Cost Function: Draw a Line, Score It
Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.
Gradient Descent Explained: Feel the Slope, Step Downhill
Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.
Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.
Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.