Machine Learning Lab / Supervised Learning / Naive Bayes
Classification
Algorithm 06 · Supervised learning

Naive Bayes

Naive Bayes makes a smart guess using probability. It looks at clues in an example and calculates which group is more likely.

Build a tiny email spam detector and watch its scores change as you select words.

ProbabilityMain idea
FastOften quick to train
TextA common use

What does it do?

It predicts a class, such as Spam or Not Spam, by comparing how likely the clues are in each class.

It is called “Bayes” because it uses Bayes’ theorem. It is called “naive” because it assumes clues are independent once the class is known.

How does it learn?

  1. Count how often each class appears.
  2. Learn how often each clue appears in each class.
  3. Use the counts to calculate probabilities.
  4. Choose the class with the highest score.
Interactive playground

Build an email and predict its class

Select the words in a message. This small teaching dataset updates the class scores as you change your selection.

Choose some words to begin

The model will compare the two class scores.

Class scores

Spam
—
Not spam
—

Choose a dataset to see its class balance.

Select words. The score combines the class prior with the likelihood of each selected word.

Bayes’ theorem

Bayes’ theorem updates a probability after we see new information.

P(Class | Words) =
[P(Words | Class) × P(Class)] / P(Words)

In simple words: the chance of a class after seeing the words depends on how well the words fit that class and how common the class was before seeing them.

Why “naive”?

It treats each selected word as if it gives separate information once the class is known.

P(Words | Class) ≈
P(word₁ | Class) × P(word₂ | Class) × ...

This is not always true in real language, but it makes the model simple and fast.

Important terms

TermMeaning
PriorHow common a class is before checking clues.
LikelihoodHow likely a clue is inside a particular class.
PosteriorThe updated probability after seeing clues.
Laplace smoothingAdds a small count so an unseen word does not make the whole score zero.

Worked numerical example

Imagine 10 training emails: 4 are spam and 6 are normal. “Free” appears in 3 spam emails and 1 normal email. Use Laplace smoothing with two possible outcomes: word present or absent.

QuantitySpamNot spam
Emails in class46
Emails containing “free”31
Prior4/10 = 0.406/10 = 0.60
Smoothed likelihood(3+1)/(4+2) = 0.667(1+1)/(6+2) = 0.25

Unscaled scores:

Spam: 0.40 × 0.667 = 0.2668
Not spam: 0.60 × 0.25 = 0.1500

The spam score is larger, so this example is classified as Spam. A real model compares all words and can normalise the scores so they add up to 1.

How do we test it?

Use data the model did not train on. Compare its predictions with the correct answers.

  • Accuracy: how many predictions were correct.
  • Precision: how many predicted positives were truly positive.
  • Recall: how many real positives were found.
  • F1-score: a balance of precision and recall.

Strengths and limits

Strengths

  • Fast and simple.
  • Often useful for text features.
  • Can work with many features.

Limits

  • Its independence assumption is often unrealistic.
  • Probability estimates may not be perfectly calibrated.
  • Results depend on useful features and data.

Three common types

TypeBest suited forExample
MultinomialCounts, such as word countsEmail or news text
BernoulliBinary features: present or absentWhether a word appears
GaussianContinuous number featuresMeasurements such as height

Python implementation

This example uses Multinomial Naive Bayes with scikit-learn.

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

emails = [
    "win a free prize now",
    "free offer claim your prize",
    "team meeting about the project",
    "please review the project report",
    "win a special offer",
    "meeting schedule for tomorrow"
]
labels = ["spam", "spam", "normal", "normal", "spam", "normal"]

model = make_pipeline(CountVectorizer(), MultinomialNB())
model.fit(emails, labels)

new_email = ["free prize offer"]
print("Prediction:", model.predict(new_email)[0])
print("Probabilities:", model.predict_proba(new_email))

Install scikit-learn first if needed: pip install scikit-learn.

Where is Naive Bayes used?

Email filtering

Spotting likely spam messages.

Sentiment analysis

Sorting reviews into positive or negative groups.

News sorting

Grouping articles by topic.

Document tagging

Finding likely categories for text.

Knowledge check

Test what you learned

Answer all 10 questions, then submit to see your score and explanations.

0 of 10 answered