Sentiment analysis with Naive Bayes

Naive Bayes solves the same sentiment task using probability. For each word it calculates: how likely is this word in a positive review, and in a negative one? Multiply those ratios across the words of a new review. Above 1 means positive; below 1 means negative. Laplace smoothing adds 1 to every count so that unseen words don't make a probability zero, and using logarithms turns the multiplication into a simple sum.

Everyday analogy

A detective weighing clues. Each clue (word) makes one suspect (positive or negative) a bit more or less likely. No single clue decides the case, but together they point clearly to an answer.

Example

Using the same four training reviews: each class has 7 words in total, and the vocabulary has 10 different words. With Laplace smoothing, P(word | class) = (count + 1) ÷ (7 + 10).

😊Positive reviews• great × 12• love × 9• fast × 6😞Negative reviews• broke × 11• waste × 7• slow × 6VS
Naive Bayes compares how often each word appears in positive and negative examples.

Probabilities for the words in "love the phone"

WordP(word | positive)P(word | negative)Ratio (pos ÷ neg)log of ratio
love(2+1)/17 = 0.176(0+1)/17 = 0.0593+1.10
the(1+1)/17 = 0.118(1+1)/17 = 0.11810
phone(1+1)/17 = 0.118(0+1)/17 = 0.0592+0.69
Total (the prior is 1, because there are 2 positive and 2 negative reviews)3 × 1 × 2 = 6+1.79

The log-likelihood score is above 0 (the ratio is above 1), so the review is positive. A word like "the" with a ratio of 1 is neutral and doesn't move the score.

Why it works well

  • Very fast to train: it only needs counting
  • Works with small datasets
  • Easy to see which words push towards positive or negative

Its limits

  • Assumes words are independent, ignoring word order
  • "not good" can fool it, because "good" is a positive word
  • Sarcasm ("great, another delay!") is hard

Try it yourself

About 15 min

Count words per class

  1. Collect 5 positive and 5 negative short reviews.
  2. Count how often key words appear in each group.
  3. Classify a new review by which group its words appear in more.

What you should see: Naive Bayes sentiment is counting words and comparing chances.

Use any free AI chatbot (ChatGPT, Claude, Gemini or Copilot). Never paste private or confidential information.

Build it for real · guided projectBuild a sentiment analyser for product reviewsAbout 60 min · Copy-paste code · step by step
Test what you learned

Take a quick quiz, or look up any word in the glossary.