Gradient LabStart the lesson

Lessons › Chapter 4: Classification

Naive Bayes

We have 100 old emails, already sorted by a person: 40 spam (coral) and 60 normal (teal). So before reading a single word, the chance that any email is spam is 40%.

Watch it move. This lesson is interactive on Gradient Lab: every step is an animated scene you can replay.

Start the interactive lesson

Step by step

Story

Phishing emails

Customers keep forwarding suspicious emails. Leo wants a quick filter based on telltale words.

Concept

Learn from old emails

We have 100 old emails, already sorted by a person: 40 spam (coral) and 60 normal (teal). So before reading a single word, the chance that any email is spam is 40%.

Build

Words are clues

Count how often each word shows up in each pile. “free” appears in 60% of spam but only 5% of normal emails, so it’s a strong spam clue. “meeting” points the other way.

Key idea

Multiply the clues

A new email says “free money”. Start from each pile’s share, then multiply by how likely each word is in that pile. Spam gets 0.4 × 0.6 × 0.5 = 0.12. Normal gets 0.6 × 0.05 × 0.1 = 0.003.

Build

Turn scores into a chance

Divide the spam score by the total of both scores: 0.12 / 0.123 ≈ 98% chance of spam. Into the spam folder it goes.

Insight

Why “naive”?

It treats each word as a separate clue, as if “free” and “money” had nothing to do with each other. That’s the naive part, and it’s not really true. Yet it works surprisingly well, and it’s very fast.

Real life

In real life: word clues in your inbox

Many early spam filters were built exactly like this: count which words show up in junk mail, then combine the clues for each new email. The same idea still helps sort support tickets and reviews by topic.

Quick check: A word appears in 70% of spam and 70% of normal emails. As a clue, it is…

A clue only helps if it’s more common in one pile than the other.

Pseudocode

# learn from 100 old emails
chance(spam) = 40 / 100
chance("free" | spam) = 0.60    chance("free" | normal) = 0.05
chance("money" | spam) = 0.50   chance("money" | normal) = 0.10

# new email: "free money"
spam_score   = 0.4 × 0.60 × 0.50    # 0.12
normal_score = 0.6 × 0.05 × 0.10    # 0.003
chance it is spam = spam_score / (spam_score + normal_score)   # 98%

Key terms

naive
Here: treating each clue as if it had nothing to do with the others.

Build it: Spam filter with Naive Bayes (30 min, runs in your browser)

See the project