Modules / NLP / Text Classification with Naive Bayes

Text Classification with Naive Bayes

Type a sentence and watch Naive Bayes score each word's evidence for positive or negative, then classify.

Input Sentence

Prior Probabilities

P(positive)
0.500
P(negative)
0.500

Word Evidence

Click Classify to see word contributions

Overview

Type a sentence and watch Naive Bayes score each word's evidence for positive or negative, then classify.

In this guide
  1. What Naive Bayes assumes
  2. The maths
  3. Why log-probabilities
  4. Laplace smoothing
  5. Where it works and where it fails
  6. A Naive Bayes classifier from scratch
  7. When to pick it
  8. Questions people ask about Text Classification with Naive Bayes

Text Classification with Naive Bayes

Multiply word probabilities under each class label and pick the winner. The maths is one line, the assumption is wrong, and the classifier works anyway.

What Naive Bayes assumes

You have a document and a set of class labels. Naive Bayes treats the document as a bag of words. It assumes every word is independent of every other word, given the class. That is plainly false. "Not" changes the sense of every word after it, and "New York" is not the same as "New idea". The model ignores all of that.

The payoff: the joint probability of all the words splits into a product of single-word probabilities. You can get those from counts alone. No optimiser, no matrix algebra, no GPU. One pass through the data builds the whole model.

This makes Naive Bayes one of the fastest classifiers to train and one of the simplest to understand. The maths fits on one line, and the code fits in a single function.

The maths

For a document d made of words w1, w2, …, wn, Bayes' theorem gives:

P(class | d) ∝ P(class) × ∏ P(wi | class)

P(class) is the prior: how big a share of training docs belong to that class. P(wi | class) is how often word wi shows up in docs of that class. Get both from counts, multiply, and pick the class with the top score.

That is the full method. The widget above lets you type a phrase and watch each word push for or against each class.

Why log-probabilities

Multiplying many small numbers gives a result so tiny that the computer rounds it to zero. A document with 200 words can push the product below 10−300. That underflows in 64-bit floating point.

The fix: work in log space. Log is monotonic, so the class that wins the product also wins the sum of logs:

log P(class | d) = log P(class) + ∑ log P(wi | class)

Addition is cheaper than multiplication and never underflows. Every real implementation does this, and the widget above shows it.

Laplace smoothing

A word that never appeared in positive training docs gets P(word | positive) = 0. One zero in the product makes the whole product zero. One unseen word vetoes the entire call.

Laplace smoothing (add-1 smoothing) fixes this by adding 1 to every word count:

P(w | class) = (count(w, class) + 1) / (total words in class + V)

V is the vocab size. The bottom grows by V so the numbers still sum to 1. No word ever has zero probability. The price: rare words get a slight boost, but this is almost always worth it.

You can swap 1 for a smaller α to smooth less. α = 1 is the most common choice.

Where it works and where it fails

Naive Bayes works well for:

  • Spam filtering. Bag-of-words is a natural fit because spam is about which words appear, not their exact order.
  • Sentiment. Words like "excellent", "terrible" and "bad" carry strong class signal on their own.
  • Topic sorting. Sport docs contain sport words; politics docs contain politics words.
  • Medical triage. Routing clinic notes by specialty based on word counts.

It struggles when:

  • Word order matters. "The movie was not good" and "The movie was good, not bad" share most words but mean different things. Naive Bayes cannot tell them apart.
  • Words interact. "Hot dog" means something else than "hot" and "dog" on their own.
  • Classes depend on absence. Some groups are defined by which words do *not* appear. A bag-of-words model has no good way to capture that.

When order matters, n-grams help a bit by treating word pairs as features. For deeper meaning, embeddings capture what counts miss, and text encoding explains why you need to turn text into numbers at all.

A Naive Bayes classifier from scratch

import math
from collections import Counter, defaultdict

train = [
    ("I love this movie", "positive"),
    ("great film and wonderful acting", "positive"),
    ("terrible waste of time", "negative"),
    ("awful movie I hated it", "negative"),
]

class_counts = Counter()
word_counts  = defaultdict(Counter)
vocab = set()
for text, label in train:
    words = text.lower().split()
    class_counts[label] += 1
    for w in words:
        word_counts[label][w] += 1
        vocab.add(w)

V = len(vocab)
total = sum(class_counts.values())

def classify(text):
    words = text.lower().split()
    scores = {}
    for label in class_counts:
        log_p = math.log(class_counts[label] / total)
        n = sum(word_counts[label].values())
        for w in words:
            log_p += math.log((word_counts[label][w] + 1) / (n + V))
        scores[label] = log_p
    return max(scores, key=scores.get), scores

pred, scores = classify("I love great acting")
print(f"Prediction: {pred}")
for label, s in scores.items():
    print(f"  {label}: {s:.4f}")

The code uses Laplace smoothing (the +1 in the top) and works in log space. It trains in one pass and classifies in time that grows with the document length times the number of classes.

When to pick it

Naive Bayes is a good first try for any text sorting task. It trains fast, needs little data, and gives a strong baseline. If the baseline is good enough, ship it. If not, you know the floor. Swap in logistic regression or a neural model later and compare against the Naive Bayes score.

In a real pipeline you often keep Naive Bayes as a cheap first filter. A spam system, for instance, might run Naive Bayes on every message and only send the uncertain ones to a slower, more accurate model. This two-stage design keeps latency low while still catching the hard cases.

Scikit-learn makes it one line: MultinomialNB().fit(X_train, y_train). The input X is usually a count matrix from CountVectorizer, where each row is a document and each column is a word. The fit call builds the log-probability table in a single pass.

Questions people ask about Text Classification with Naive Bayes

Is Naive Bayes really "naive"? Yes. Words in real text are not independent. But the classifier needs the right ranking, not the right probability, and the wrong assumption rarely flips the winner.

When to pick it over logistic regression? When you have little data, many features, or need a fast baseline. Fewer weights to fit means it handles sparse data well. With enough data, logistic regression usually wins.

Does it work with TF-IDF? The basic form uses raw counts. If you want TF-IDF, complement Naive Bayes or logistic regression is a better fit. Scikit-learn has both.

Multinomial vs Bernoulli — what is the difference? Multinomial uses word counts. Bernoulli uses just yes or no — did the word appear? For short texts like tweets, Bernoulli can work better because repeats add little info.

Can it handle more than two classes? Yes. The formula works for any number of classes. You compute the prior and the word scores for each class on its own, then pick the top one.

Why does it still show up in production? It trains in milliseconds, classifies in microseconds, and gives a strong floor. Many spam filters and content classifiers still run it, sometimes as the first stage that sends hard cases to a heavier model.

Predict, then reveal

About to run: press Classify. Before it does — what happens to the readout?

Committing to an answer first is the point — the reveal runs the experiment on the visualisation above and reads the real value back, so nothing here is scripted.

Recall check

0 of 3

Say the answer out loud before you reveal it — recalling it is what makes it stick, and rereading it is not.

  1. What does this module say about “What Naive Bayes assumes”?

  2. What does this module say about “Why log-probabilities”?

  3. What does this module say about “Laplace smoothing”?

Cheat sheet

Text Classification with Naive Bayes

Type a sentence and watch Naive Bayes score each word's evidence for positive or negative, then classify.

NLP · vizlearn.in/natural_language_processing/text_classification_with_naive_bayes.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.

Teaching a course with this? Individual teachers can use it freely; for a whole department or programme, see institutional licences.