Text Classification with Naive Bayes
Type a sentence and watch Naive Bayes score each word's evidence for positive or negative, then classify.
Type a sentence and watch Naive Bayes score each word's evidence for positive or negative, then classify.
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.
Type a sentence and watch Naive Bayes score each word's evidence for positive or negative, then classify.
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.
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.
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.
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.
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.
Naive Bayes works well for:
It struggles when:
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.
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.
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.
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.
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.
Say the answer out loud before you reveal it — recalling it is what makes it stick, and rereading it is not.
What does this module say about “What Naive Bayes assumes”?
What does this module say about “Why log-probabilities”?
What does this module say about “Laplace smoothing”?
Type a sentence and watch Naive Bayes score each word's evidence for positive or negative, then classify.