惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Recent Announcements
Recent Announcements
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Application and Cybersecurity Blog
Application and Cybersecurity Blog
N
News | PayPal Newsroom
P
Proofpoint News Feed
L
Lohrmann on Cybersecurity
S
Security @ Cisco Blogs
K
Kaspersky official blog
A
Arctic Wolf
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Project Zero
Project Zero
L
LINUX DO - 最新话题
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The Last Watchdog
The Last Watchdog
T
The Exploit Database - CXSecurity.com
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Security Archives - TechRepublic
Security Archives - TechRepublic
V
V2EX
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
H
Hackread – Cybersecurity News, Data Breaches, AI and More
爱范儿
爱范儿
F
Full Disclosure
I
Intezer
Schneier on Security
Schneier on Security
AWS News Blog
AWS News Blog
C
Cybersecurity and Infrastructure Security Agency CISA
博客园 - 聂微东
M
MIT News - Artificial intelligence
P
Privacy & Cybersecurity Law Blog
Attack and Defense Labs
Attack and Defense Labs
量子位
Google DeepMind News
Google DeepMind News
T
Threat Research - Cisco Blogs
Last Week in AI
Last Week in AI
Google Online Security Blog
Google Online Security Blog
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
Microsoft Security Blog
Microsoft Security Blog
Scott Helme
Scott Helme
C
Check Point Blog
N
Netflix TechBlog - Medium
博客园 - Franky
SecWiki News
SecWiki News
Know Your Adversary
Know Your Adversary
Engineering at Meta
Engineering at Meta
F
Fortinet All Blogs
Blog — PlanetScale
Blog — PlanetScale
S
Securelist

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
62. Naive Bayes: Fast, Simple, Surprisingly Effective
Akhilesh · 2026-05-10 · via DEV Community

Your email spam filter makes a decision in milliseconds. Thousands of words. Instant classification.

Most of the algorithms we've covered so far would struggle with that. KNN needs to compute distances across thousands of features. SVM slows down on high dimensions. Even tree-based models take time.

Naive Bayes does it in one pass. It counts words, multiplies probabilities, picks the class with the highest probability. Done.

It's been doing this since the 1990s and it still works.


What You'll Learn Here

  • What Bayes theorem is in plain words, not symbols
  • Why the naive assumption works even when it is wrong
  • The three variants: Gaussian, Multinomial, Bernoulli
  • Building a text classifier from scratch
  • When Naive Bayes wins and when it loses
  • Full working code with scikit-learn

Bayes Theorem in Plain English

You want to know: given that this email contains the word "casino", what is the probability it is spam?

That's a conditional probability. Written as:

P(spam | word="casino")

Enter fullscreen mode Exit fullscreen mode

Bayes theorem says you can calculate this using things you already know from training data:

P(spam | casino) = P(casino | spam) * P(spam)
                   ─────────────────────────────
                          P(casino)

Enter fullscreen mode Exit fullscreen mode

In words:

  • P(casino | spam): how often does the word "casino" appear in spam emails? You know this from training data.
  • P(spam): what fraction of all emails are spam? You know this too.
  • P(casino): how often does "casino" appear in any email? Also known.

So you can calculate the probability that an email is spam, given that it contains "casino", using just counts from your training data.

For classification, you don't even need the denominator P(casino) because it's the same for all classes. You just compare:

P(spam | casino)     vs     P(not spam | casino)

Whichever is bigger wins.

Enter fullscreen mode Exit fullscreen mode


Why It's Called Naive

Real emails have many words. You need:

P(spam | word1, word2, word3, ..., word1000)

Enter fullscreen mode Exit fullscreen mode

Calculating the joint probability of all those words together is nearly impossible. The data would never be enough.

The naive assumption: treat every word as independent of every other word. Pretend that seeing the word "casino" tells you nothing about whether "free" also appears.

P(spam | word1, word2, ..., wordN)
  ≈ P(word1 | spam) * P(word2 | spam) * ... * P(wordN | spam) * P(spam)

Enter fullscreen mode Exit fullscreen mode

Now you just multiply individual word probabilities. Those you can estimate easily from training data.

Is this assumption true? Absolutely not. Words in emails are not independent at all. "Free money" tends to appear together in spam.

Does it work anyway? Yes. Shockingly well.

The reason it still works is that even wrong independence assumptions lead to the right class comparison most of the time. The relative ordering of class probabilities tends to be preserved even when the absolute probabilities are wrong.


Three Variants of Naive Bayes

Different variants handle different types of features.

Gaussian Naive Bayes
For continuous features. Assumes each feature follows a normal (Gaussian) distribution within each class.

Multinomial Naive Bayes
For count data. Most common for text classification using word counts or TF-IDF.

Bernoulli Naive Bayes
For binary features. Good for text where you only care whether a word appears, not how many times.


Gaussian Naive Bayes on Numeric Data

from sklearn.naive_bayes import GaussianNB
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score, classification_report

iris = load_iris()
X, y = iris.data, iris.target

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

gnb = GaussianNB()
gnb.fit(X_train, y_train)

y_pred = gnb.predict(X_test)
print(f"Gaussian NB Accuracy: {accuracy_score(y_test, y_pred):.3f}")
print()
print(classification_report(y_test, y_pred, target_names=iris.target_names))

Enter fullscreen mode Exit fullscreen mode

Output:

Gaussian NB Accuracy: 0.967

              precision    recall  f1-score   support

      setosa       1.00      1.00      1.00        10
  versicolor       1.00      0.90      0.95        10
   virginica       0.91      1.00      0.95        10

    accuracy                           0.97        30

Enter fullscreen mode Exit fullscreen mode

What the model actually learned: for each feature and each class, it calculated the mean and variance. At prediction time, it checks how likely each feature value is under each class's distribution.

# What GaussianNB learned
import pandas as pd
import numpy as np

print("Class means for each feature:")
means_df = pd.DataFrame(
    gnb.theta_,
    columns=iris.feature_names,
    index=iris.target_names
)
print(means_df.round(2))

Enter fullscreen mode Exit fullscreen mode

Output:

Class means for each feature:
            sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)
setosa                   5.01              3.43               1.46              0.25
versicolor               5.94              2.77               4.26              1.33
virginica                6.59              2.97               5.55              2.03

Enter fullscreen mode Exit fullscreen mode

These means tell the whole story. Virginica has the longest petals. Setosa has the shortest. When a new flower comes in, the model checks which class's distribution it fits best.


Multinomial Naive Bayes for Text Classification

This is where Naive Bayes really shines. Let's build a spam classifier.

from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
import pandas as pd
import numpy as np

# Simple spam dataset
emails = [
    # Spam
    ("Get rich quick! Free money! Click here now!", 1),
    ("You won a prize! Claim your free casino chips!", 1),
    ("Cheap meds online! No prescription needed!", 1),
    ("URGENT: Your account needs verification. Click now!", 1),
    ("Make money from home! Easy income guaranteed!", 1),
    ("Free Viagra! Cialis! Lowest prices online!", 1),
    ("Congratulations you have been selected for a prize!", 1),
    ("Win big today! Limited time casino offer!", 1),
    # Not spam
    ("Hey, are we still meeting for lunch tomorrow?", 0),
    ("The quarterly report is ready for your review.", 0),
    ("Can you send me the project files?", 0),
    ("Meeting rescheduled to 3pm on Thursday.", 0),
    ("Your order has been shipped. Track it here.", 0),
    ("Thanks for the presentation today, great work!", 0),
    ("Please review the attached document and let me know.", 0),
    ("Team lunch is on Friday at noon, see you there!", 0),
]

texts, labels = zip(*emails)
texts  = list(texts)
labels = list(labels)

X_train, X_test, y_train, y_test = train_test_split(
    texts, labels, test_size=0.25, random_state=42
)

# Convert text to word counts
vectorizer = CountVectorizer(stop_words='english', lowercase=True)
X_train_counts = vectorizer.fit_transform(X_train)
X_test_counts  = vectorizer.transform(X_test)

# Train Multinomial NB
mnb = MultinomialNB(alpha=1.0)  # alpha=1 is Laplace smoothing
mnb.fit(X_train_counts, y_train)

y_pred = mnb.predict(X_test_counts)
print(f"Accuracy: {accuracy_score(y_test, y_pred):.3f}")
print()
print(classification_report(y_test, y_pred, target_names=['not spam', 'spam']))

Enter fullscreen mode Exit fullscreen mode


What the Model Learned About Words

This is the most interesting part. You can see exactly which words push toward spam and which toward not-spam.

# Get feature names (words)
feature_names = vectorizer.get_feature_names_out()

# Log probabilities for each class
log_probs = mnb.feature_log_prob_  # shape: (n_classes, n_features)

# Top spam words
spam_log_probs   = log_probs[1]
notspam_log_probs = log_probs[0]

# Words most associated with spam
spam_word_scores = pd.DataFrame({
    'Word':      feature_names,
    'Spam prob': np.exp(spam_log_probs),
    'Ham prob':  np.exp(notspam_log_probs),
    'Diff':      spam_log_probs - notspam_log_probs
}).sort_values('Diff', ascending=False)

print("Top words that scream SPAM:")
print(spam_word_scores.head(10)[['Word', 'Diff']].to_string(index=False))

print("\nTop words that scream NOT SPAM:")
print(spam_word_scores.tail(10)[['Word', 'Diff']].to_string(index=False))

Enter fullscreen mode Exit fullscreen mode


Classify New Emails

new_emails = [
    "Free money! You won! Click here!",
    "Can we schedule a call for next week?",
    "Exclusive casino offer just for you, free chips!",
    "The project deadline has been moved to Friday.",
]

new_counts = vectorizer.transform(new_emails)
predictions = mnb.predict(new_counts)
probabilities = mnb.predict_proba(new_counts)

for email, pred, proba in zip(new_emails, predictions, probabilities):
    label = "SPAM" if pred == 1 else "NOT SPAM"
    print(f"[{label}] (confidence: {max(proba):.1%})")
    print(f"  '{email[:60]}...' " if len(email) > 60 else f"  '{email}'")
    print()

Enter fullscreen mode Exit fullscreen mode

Output:

[SPAM] (confidence: 99.8%)
  'Free money! You won! Click here!'

[NOT SPAM] (confidence: 94.2%)
  'Can we schedule a call for next week?'

[SPAM] (confidence: 99.1%)
  'Exclusive casino offer just for you, free chips!'

[NOT SPAM] (confidence: 91.7%)
  'The project deadline has been moved to Friday.'

Enter fullscreen mode Exit fullscreen mode


TF-IDF Instead of Raw Counts

Raw word counts give too much weight to common words. TF-IDF (Term Frequency-Inverse Document Frequency) adjusts for this. Words that appear in many documents get lower weight.

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline

# Pipeline with TF-IDF
tfidf_pipeline = Pipeline([
    ('tfidf', TfidfVectorizer(stop_words='english', lowercase=True)),
    ('nb',    MultinomialNB(alpha=0.1))
])

tfidf_pipeline.fit(X_train, y_train)
y_pred_tfidf = tfidf_pipeline.predict(X_test)
print(f"TF-IDF + Naive Bayes Accuracy: {accuracy_score(y_test, y_pred_tfidf):.3f}")

Enter fullscreen mode Exit fullscreen mode


Bernoulli Naive Bayes

When you only care if a word appears at all, not how many times:

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

# BernoulliNB works with binary features (word present or not)
bin_vectorizer = CountVectorizer(binary=True, stop_words='english')
X_train_bin = bin_vectorizer.fit_transform(X_train)
X_test_bin  = bin_vectorizer.transform(X_test)

bnb = BernoulliNB(alpha=1.0)
bnb.fit(X_train_bin, y_train)

y_pred_b = bnb.predict(X_test_bin)
print(f"Bernoulli NB Accuracy: {accuracy_score(y_test, y_pred_b):.3f}")

Enter fullscreen mode Exit fullscreen mode

When to use which:

  • Gaussian NB: continuous numeric features
  • Multinomial NB: word counts, TF-IDF, frequency data
  • Bernoulli NB: binary features, short text, word presence/absence

Laplace Smoothing: Handling Unseen Words

What if a word appears in test data but never appeared in training? Its probability would be 0. And 0 multiplied by anything is 0. The whole prediction collapses.

Laplace smoothing fixes this by adding a small count to every word, even unseen ones.

# alpha controls smoothing
# alpha=1.0 is classic Laplace smoothing
# alpha=0.1 is lighter smoothing - better when you have lots of data

for alpha in [0.01, 0.1, 0.5, 1.0, 2.0, 5.0]:
    mnb_a = MultinomialNB(alpha=alpha)
    mnb_a.fit(X_train_counts, y_train)
    acc = accuracy_score(y_test, mnb_a.predict(X_test_counts))
    print(f"alpha={alpha:<5} accuracy={acc:.3f}")

Enter fullscreen mode Exit fullscreen mode

Alpha=1.0 is the safe default. On larger datasets try smaller values like 0.1.


Real Dataset: 20 Newsgroups

Let's test on a real text classification dataset with 20 categories.

from sklearn.datasets import fetch_20newsgroups
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import Pipeline
from sklearn.metrics import accuracy_score
import time

# Load 4 categories for speed
categories = ['sci.space', 'rec.sport.hockey', 'talk.politics.guns', 'comp.graphics']

train_data = fetch_20newsgroups(subset='train', categories=categories, remove=('headers', 'footers'))
test_data  = fetch_20newsgroups(subset='test',  categories=categories, remove=('headers', 'footers'))

print(f"Training documents: {len(train_data.data)}")
print(f"Testing documents:  {len(test_data.data)}")
print(f"Categories: {categories}")

# Build and train pipeline
pipeline = Pipeline([
    ('tfidf', TfidfVectorizer(max_features=10000, stop_words='english')),
    ('nb',    MultinomialNB(alpha=0.1))
])

start = time.time()
pipeline.fit(train_data.data, train_data.target)
train_time = time.time() - start

start = time.time()
y_pred = pipeline.predict(test_data.data)
predict_time = time.time() - start

acc = accuracy_score(test_data.target, y_pred)
print(f"\nAccuracy:     {acc:.3f}")
print(f"Train time:   {train_time:.3f}s")
print(f"Predict time: {predict_time:.3f}s")

Enter fullscreen mode Exit fullscreen mode

Output:

Training documents: 2169
Testing documents:  1444
Categories: ['sci.space', 'rec.sport.hockey', 'talk.politics.guns', 'comp.graphics']

Accuracy:     0.941
Train time:   0.043s
Predict time: 0.008s

Enter fullscreen mode Exit fullscreen mode

94.1% accuracy. Trained in 0.04 seconds. Predicted 1444 documents in 0.008 seconds.

That speed is the whole point. Neural networks will get higher accuracy on text. But if you need something fast, interpretable, and good enough, Naive Bayes is hard to beat.


When Naive Bayes Wins and When to Skip It

Use Naive Bayes when:

  • Text classification: spam, sentiment, topic classification
  • Dataset is small. NB needs very little data to work well.
  • You need fast training and prediction at scale
  • You want a quick, solid baseline before trying complex models
  • Features are truly or mostly independent (rare but happens)

Skip Naive Bayes when:

  • Features are strongly correlated. The naive assumption causes big problems.
  • You need very high accuracy and have enough data for complex models
  • Numeric features with complex non-linear relationships
  • You need probability estimates to be accurate, not just the class ranking

Comparing All Three Variants

from sklearn.naive_bayes import GaussianNB, MultinomialNB, BernoulliNB
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import MinMaxScaler  # MultinomialNB needs non-negative input

data = load_breast_cancer()
X_bc, y_bc = data.data, data.target

# MinMaxScaler for MultinomialNB (needs non-negative features)
X_scaled = MinMaxScaler().fit_transform(X_bc)

models = {
    'GaussianNB':     (GaussianNB(),           X_bc),
    'MultinomialNB':  (MultinomialNB(alpha=1), X_scaled),
    'BernoulliNB':    (BernoulliNB(alpha=1),   X_bc),
}

print(f"{'Model':<18} {'CV Mean':<10} {'CV Std'}")
print("-" * 38)

for name, (model, X_use) in models.items():
    scores = cross_val_score(model, X_use, y_bc, cv=5)
    print(f"{name:<18} {scores.mean():.3f}      {scores.std():.3f}")

Enter fullscreen mode Exit fullscreen mode

Output:

Model              CV Mean    CV Std
--------------------------------------
GaussianNB         0.939      0.020
MultinomialNB      0.898      0.022
BernoulliNB        0.627      0.033

Enter fullscreen mode Exit fullscreen mode

GaussianNB wins on numeric data as expected. MultinomialNB is mediocre on numeric data but excellent on text. BernoulliNB is binary-focused and struggles with continuous values.


Quick Cheat Sheet

Task Code
Numeric features GaussianNB()
Word counts / TF-IDF MultinomialNB(alpha=1.0)
Binary features BernoulliNB(alpha=1.0)
Text vectorization TfidfVectorizer(stop_words='english')
Full text pipeline Pipeline([('tfidf', TfidfVectorizer()), ('nb', MultinomialNB())])
Get probabilities .predict_proba(X)
See word probs np.exp(model.feature_log_prob_)
Tune smoothing try alpha values 0.01 to 5.0

Practice Challenges

Level 1:
Load the 20 Newsgroups dataset with all 20 categories. Train a TF-IDF + MultinomialNB pipeline. Print overall accuracy and the classification report. Which categories does it confuse most?

Level 2:
On the breast cancer dataset, compare GaussianNB to LogisticRegression and KNN. Where does NB fall short? Is the gap large or small?

Level 3:
Build a sentiment classifier. Use any small movie review or product review dataset (the movie_reviews corpus from NLTK works). Compare CountVectorizer vs TfidfVectorizer with MultinomialNB. Which gives better accuracy? Try tuning alpha with cross-validation.


References


Next up, Post 63: Confusion Matrix: What Your Model Got Wrong and Why. TP, TN, FP, FN explained properly with real examples. The one tool that tells you exactly where your model is failing.