Naive Bayes classifiers use probability and Bayes’ theorem. They are extremely fast, need little data, and are a strong baseline for text classification such as spam filtering.
What You Will Learn
- Bayes’ theorem
- The “naive” independence assumption
- Gaussian, Multinomial and Bernoulli variants
- Training GaussianNB
Prerequisites
Basic probability and Logistic Regression.
Bayes’ Theorem
P(class | features) = P(features | class) × P(class) / P(features)
In words: the chance of a class given what we see equals how likely those features are for that class, times how common the class is, scaled by how common the features are overall. The model predicts the class with the highest result.
Why “Naive”?
It assumes every feature is independent of the others given the class, so P(features | class) is just the product of each feature’s probability. This is rarely true (tumour radius and area are clearly related), yet the classifier often still works well.
Worked Example
Suppose 30% of emails are spam. “Free” appears in 60% of spam and 5% of normal emails. For an email containing “free”:
spam score = 0.6 × 0.3 = 0.18; normal score = 0.05 × 0.7 = 0.035.
P(spam | free) = 0.18 / (0.18 + 0.035) ≈ 0.84, so it is classified as spam.
Step 1: Data
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
import pandas as pd
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
print(X.shape, y.value_counts().to_dict())
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y)
def evaluate(name, model):
model.fit(X_train, y_train)
p = model.predict(X_test)
print(f'{name:26s} acc={accuracy_score(y_test, p):.3f}')
return model, p
Explanation: We use the built-in Breast Cancer Wisconsin dataset: 569 tumour samples, 30 numeric measurements each, and a label 0 = malignant or 1 = benign. stratify=y keeps the same class balance in the train and test sets. Every classification tutorial in this series uses this exact split, so you can compare algorithms fairly.
(569, 30) {1: 357, 0: 212}
Step 2: Gaussian Naive Bayes
from sklearn.naive_bayes import GaussianNB
nb, pnb = evaluate('GaussianNB', GaussianNB())
Explanation: GaussianNB assumes each feature is normally distributed within each class. It trains in a fraction of a second and needs no scaling.
GaussianNB acc=0.939
Which Variant?
| Model | Features | Typical use |
|---|---|---|
| GaussianNB | Continuous numbers | Measurements |
| MultinomialNB | Counts | Word counts in text |
| BernoulliNB | 0/1 presence | Word present or not |
| ComplementNB | Counts, imbalanced | Imbalanced text classes |
Text Example
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
texts = ['win free money now', 'free lottery prize', 'meeting at 10 tomorrow', 'project report attached']
labels = ['spam', 'spam', 'ham', 'ham']
clf = make_pipeline(CountVectorizer(), MultinomialNB()).fit(texts, labels)
print(clf.predict(['free prize money', 'report for the meeting']))
['spam' 'ham']
Practice Exercises
- Build a spam classifier on the SMS Spam Collection dataset with MultinomialNB.
Interview Questions
Q: What is the naive assumption?
Features are conditionally independent given the class.
Q: Why is Naive Bayes good for text?
It handles thousands of features quickly and works well with little data.
Summary
Naive Bayes applies Bayes’ theorem with an independence assumption. Use GaussianNB for numbers and MultinomialNB for word counts.
Next: K-Nearest Neighbor · NLP tutorials
Machine Learning Tutorials, Courses and Certifications