Reading history

Naive Bayes Classifier in Python (Spam Filter Example)

5 min read 0 views

Learn Naive Bayes in Python with scikit-learn: Bayes' theorem, the independence assumption, MultinomialNB for text, GaussianNB and smoothing.

Naive Bayes classifiers decide between classes by asking a probability question: given these features, which class is most likely? They apply Bayes’ theorem with one bold simplification, that every feature is independent of the others once the class is known. That assumption is rarely true, yet Naive Bayes trains in a single pass, needs very little data and works remarkably well, especially for text such as spam filtering.

In this lesson you will learn

  • Bayes’ theorem in plain words
  • Why the method is called “naive”
  • Classifying text with MultinomialNB and word counts
  • Numeric features with GaussianNB
  • When Naive Bayes is a good choice

You should know train/test splits and classification metrics.

The Idea

Bayes’ theorem combines what we believed before seeing the data with how well the data fits each class:

P(class | features)  ∝  P(class) × P(feature1 | class) × P(feature2 | class) × ...
  • P(class), the prior, is how common the class is overall, for example the share of messages that are spam.
  • P(feature | class), the likelihood, is how typical a feature is within that class, for example how often “free” appears in spam.
  • Multiplying the likelihoods one by one is only valid if the features are independent within a class. Assuming this, even when words like “free” and “prize” clearly go together, is the naive part.
  • The class with the largest product wins.

Spam Detection With MultinomialNB

from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer

# A tiny SMS dataset: 1 = spam, 0 = normal message
messages = [
    "Win a free phone now", "Claim your free prize today", "Free cash bonus click now",
    "Lowest price offer win big", "Are we meeting for lunch", "Send me the class notes",
    "Call me when you reach home", "The exam starts at ten tomorrow",
]
labels = [1, 1, 1, 1, 0, 0, 0, 0]

vectorizer = CountVectorizer(lowercase=True)
X = vectorizer.fit_transform(messages)          # word counts per message
print("Vocabulary size:", len(vectorizer.vocabulary_))

model = MultinomialNB(alpha=1.0).fit(X, labels)  # alpha=1 is Laplace smoothing

tests = ["Free prize waiting for you", "See you at lunch tomorrow", "Win cash now"]
probs = model.predict_proba(vectorizer.transform(tests))
for text, p in zip(tests, probs):
    print(f"{text:28s} -> spam probability {p[1]:.2f}")

Output

Vocabulary size: 35
Free prize waiting for you   -> spam probability 0.71
See you at lunch tomorrow    -> spam probability 0.07
Win cash now                 -> spam probability 0.95
  • CountVectorizer turns each message into counts of the 35 distinct words in the training set, the classic bag of words.
  • MultinomialNB learns, for each class, how often each word appears. It is designed for count features such as these.
  • alpha=1.0 adds one imaginary occurrence of every word to every class (Laplace smoothing). Without it, a word never seen in spam would give spam a probability of exactly zero.
  • “Win cash now” contains three spam words and scores 0.95; “See you at lunch tomorrow” scores 0.07. Words not in the vocabulary, such as “waiting”, are simply ignored.

Numeric Features With GaussianNB

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)

gnb = GaussianNB().fit(X_train, y_train)
logreg = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X_train, y_train)

print(f"Gaussian Naive Bayes accuracy: {gnb.score(X_test, y_test):.3f}")
print(f"Logistic regression accuracy:  {logreg.score(X_test, y_test):.3f}")

# Naive Bayes learns just a mean and variance per feature per class
print("Learned parameters:", gnb.theta_.shape, "means and", gnb.var_.shape, "variances")
print("Class priors:", gnb.class_prior_.round(3))

Output

Gaussian Naive Bayes accuracy: 0.923
Logistic regression accuracy:  0.958
Learned parameters: (2, 30) means and (2, 30) variances
Class priors: [0.373 0.627]
  • GaussianNB assumes each numeric feature follows a bell curve within each class. Training only computes a mean and a variance for each of the 30 features in each of the 2 classes, plus the class priors.
  • On the breast cancer dataset it reaches 92.3% accuracy, a little below logistic regression’s 95.8%. The independence assumption costs some accuracy because many of these measurements are strongly related.
  • Naive Bayes needs no feature scaling, because each feature is modelled separately.

Naive Bayes Variants

ClassFeature typeTypical use
MultinomialNBCounts (word frequencies)Spam filtering, topic classification
BernoulliNBYes/no features (word present or not)Short texts, binary indicators
GaussianNBContinuous numbersSensor readings, measurements
ComplementNBCounts, imbalanced classesText with one rare class

Common Mistakes

  1. Setting alpha=0, so one unseen word zeroes out a whole class.
  2. Using GaussianNB on word counts, which are not bell-shaped; use MultinomialNB.
  3. Fitting the vectorizer on the test data; call fit_transform on training text and only transform on new text.
  4. Trusting the probabilities too much: Naive Bayes ranks classes well but its probabilities are often too extreme.

Practice Exercises

Exercise 1. Replace CountVectorizer with TfidfVectorizer in the spam example. What changes?

Show answer
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(messages)
model = MultinomialNB().fit(X, labels)

TF-IDF gives less weight to words that appear in many messages, such as “you”, and more to distinctive words. On this tiny set the three messages get the same labels, but the probabilities become less extreme (for example 0.72 instead of 0.95 for “Win cash now”). On real collections TF-IDF often improves accuracy.

Exercise 2. 20% of emails are spam. “offer” appears in 60% of spam and 5% of normal emails. Which class does Naive Bayes choose for an email containing only “offer”?

Show answer

Spam: 0.2 × 0.6 = 0.12. Normal: 0.8 × 0.05 = 0.04. Spam wins, with probability 0.12 / (0.12 + 0.04) = 0.75.

Frequently Asked Questions

Why does Naive Bayes work if its assumption is wrong?

Classification only needs the correct class to get the highest score, not accurate probabilities. Errors from the independence assumption often affect all classes similarly, so the ranking stays right.

Is Naive Bayes still used today?

Yes, as a fast baseline for text classification, in email filters, and wherever training must be quick or data is limited. It is often the first model to try before larger ones.

Summary

  • Naive Bayes multiplies a class prior by per-feature likelihoods.
  • “Naive” means features are assumed independent within each class.
  • MultinomialNB with word counts is a strong text baseline; smoothing avoids zero probabilities.
  • GaussianNB handles numeric features and needs no scaling.

Next: Support Vector Machines (SVM).

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *