Naive Bayes
Naive Bayes classifiers apply probability theory directly. They ask: given these features, which class is most probable? They are extremely fast, work with very little data and are a classic choice for text classification such as spam filtering.
Bayes' theorem
P(class | features) = P(features | class) * P(class) / P(features)P(class)— the prior: how common the class is overall.P(features | class)— the likelihood: how typical these features are for that class.P(class | features)— the posterior: what we want.
P(features) is the same for every class, so to compare classes we only need the numerator.
The "naive" part
Computing P(features | class) for all feature combinations at once would need enormous amounts of data. Naive Bayes makes a bold simplification: it assumes the features are independent given the class, so the likelihood is just a product of one-feature probabilities:
P(f1, f2, f3 | class) ≈ P(f1 | class) * P(f2 | class) * P(f3 | class)The assumption is rarely true (in an email, "free" and "prize" tend to appear together), yet the resulting classifier often works surprisingly well.
Counting by hand
Suppose we have 10 past emails, and we track two yes/no features: does the email contain the word "offer", and does it contain a link?
import pandas as pd
emails = pd.DataFrame({
"offer": [1, 1, 0, 1, 0, 0, 1, 0, 0, 0],
"link": [1, 1, 1, 0, 0, 1, 1, 0, 0, 0],
"spam": [1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
})
prior_spam = emails["spam"].mean()
spam, ham = emails[emails.spam == 1], emails[emails.spam == 0]
print(f"P(spam) = {prior_spam}")
print(f"P(offer | spam) = {spam.offer.mean():.3f} P(offer | ham) = {ham.offer.mean():.3f}")
print(f"P(link | spam) = {spam.link.mean():.3f} P(link | ham) = {ham.link.mean():.3f}")
# new email: contains "offer" and a link
score_spam = prior_spam * spam.offer.mean() * spam.link.mean()
score_ham = (1 - prior_spam) * ham.offer.mean() * ham.link.mean()
print(f"P(spam | offer, link) = {score_spam / (score_spam + score_ham):.3f}")P(spam) = 0.4
P(offer | spam) = 0.750 P(offer | ham) = 0.167
P(link | spam) = 0.750 P(link | ham) = 0.333
P(spam | offer, link) = 0.871
Dividing by the sum of both scores turns them back into proper probabilities.
Three flavours in scikit-learn
| Class | Feature type | Typical use |
|---|---|---|
GaussianNB |
continuous numbers, assumed normal within each class | measurements |
MultinomialNB |
counts (word counts) | text classification |
BernoulliNB |
binary yes/no features | word present / absent |
GaussianNB on measurements
GaussianNB models each feature within each class as a normal distribution (mean and variance learned from training data):
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)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
nb = GaussianNB().fit(X_tr, y_tr)
print("test accuracy:", round(nb.score(X_te, y_te), 3))
print("learned class priors:", nb.class_prior_.round(3))
print("mean petal length per class:", nb.theta_[:, 2].round(2))
print("probabilities for first test flower:", nb.predict_proba(X_te[:1]).round(4))test accuracy: 0.978
learned class priors: [0.333 0.333 0.333]
mean petal length per class: [1.43 4.23 5.61]
probabilities for first test flower: [[0. 0. 1.]]
MultinomialNB on text
For text, each document becomes a vector of word counts (the Working with Text lesson explains CountVectorizer in detail):
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
texts = [
"win a free prize now", "free offer click now", "cheap prize offer today",
"claim your free reward", "meeting notes for monday", "lunch with the team today",
"project report attached", "see you at the meeting",
]
labels = ["spam", "spam", "spam", "spam", "ham", "ham", "ham", "ham"]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)
model = MultinomialNB().fit(X, labels)
new = ["free prize meeting", "team report for monday", "click to claim offer"]
for text, label, proba in zip(new, model.predict(vectorizer.transform(new)),
model.predict_proba(vectorizer.transform(new))):
print(f"{text!r:26} -> {label:4} P(spam)={proba[list(model.classes_).index('spam')]:.2f}")'free prize meeting' -> spam P(spam)=0.81
'team report for monday' -> ham P(spam)=0.06
'click to claim offer' -> spam P(spam)=0.93
Smoothing
What if a word never appeared in any spam email during training? Its probability would be 0, and multiplying by 0 wipes out all other evidence. Laplace smoothing adds a small count (alpha=1.0 by default) to every word so nothing is ever exactly impossible. Smaller alpha trusts the training counts more.
Strengths and weaknesses
- ✔ Trains in a single pass over the data — very fast, even with millions of features.
- ✔ Needs little training data; handles many classes naturally.
- ✘ The independence assumption makes its probabilities overconfident (often near 0 or 1), even when its class decisions are good.
- ✘ Usually beaten by logistic regression or boosting when there's plenty of data.
Go further: Multinomial Naive Bayes for Text writes the text variant from scratch and compares the variants and their hyperparameters.
Test yourself
What does the 'naive' assumption in Naive Bayes state?
- All classes are equally likely
- Features are independent of each other given the class
- Features are normally distributed
- There are only two classes
Which Naive Bayes variant fits word-count features best?
- GaussianNB
- MultinomialNB
- BernoulliNB
- LinearRegression
Why is Laplace smoothing used?
- To speed up training
- To prevent a single unseen word from making a class probability exactly zero
- To scale features
- To remove stop words