Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 5 of 9
Naive Bayes Classifiers: Bayes Theorem, Laplace Smoothing & Text Applications
Naive Bayes classifiers are probabilistic models grounded in Bayes' Theorem: P(y|X) = P(X|y) P(y) / P(X). The 'naive' assumption posits that all features x_i are mutually conditionally independent given the class label y: P(X|y) = product(P(x_i|y)). Despite this unrealistic independence assumption, Naive Bayes performs remarkably well on high-dimensional text classification, spam filtering, and sentiment analysis due to rapid linear O(n * p) training and zero hyperparameter tuning overhead.
Multinomial Naive Bayes with Laplace Additive Smoothing
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.metrics import classification_report
# Corpus of labeled customer support inquiries
corpus = [
"Credit card was double charged for transaction yesterday",
"Cannot log in to my account password reset link expired",
"Requesting a full refund for damaged shipment order",
"Two-factor authentication code is not arriving on my phone",
"Unauthorized fraudulent charge on my banking statement",
"Unable to authenticate login portal keeps spinning",
]
labels = ["billing", "auth", "billing", "auth", "billing", "auth"]
# Construct pipeline: Count vectorization + Multinomial Naive Bayes
# alpha=1.0 applies Laplace (Add-1) smoothing to prevent zero-probability crashes
nb_pipeline = Pipeline([
("vectorizer", CountVectorizer(stop_words="english")),
("nb", MultinomialNB(alpha=1.0)),
])
nb_pipeline.fit(corpus, labels)
# Test on novel live customer tickets
test_tickets = [
"Immediate refund required for duplicate credit payment",
"Failed password authentication on mobile app",
"System was hacked and account credentials compromised",
]
predictions = nb_pipeline.predict(test_tickets)
probabilities = nb_pipeline.predict_proba(test_tickets)
for ticket, pred, prob in zip(test_tickets, predictions, probabilities):
conf = np.max(prob) * 100
print(f"Ticket: '{ticket}'\n -> Route to: [{pred.upper()}] ({conf:.1f}% confidence)\n")Pro Tip: Selecting the Right Naive Bayes Variant
Use `MultinomialNB` for discrete word counts and frequencies. Use `BernoulliNB` for binary word occurrence (word present vs absent, optimal for short micro-texts). Use `GaussianNB` for continuous real-valued measurements (assumes features follow a normal distribution within each class).
MlNaiveBayesAlgorithm Visual Representation
Hands-On Challenge: The Zero-Probability Problem
Compute class posterior probabilities with `alpha=0.0` (no smoothing) on a test sentence containing an unseen word not present in the training vocabulary. Demonstrate why the product collapses to 0.0, proving the mathematical necessity of Laplace smoothing.
Quick Quiz & Key Concept Checks
Common Pitfall: Negative Values in MultinomialNB
Multinomial Naive Bayes represents counts and frequencies; passing negative feature values (e.g., after `StandardScaler`) raises a `ValueError`. Use `MinMaxScaler` or raw counts with MultinomialNB.