Module 9 · Intermediate · Naive Bayes

Naive Bayes from scratch in Python

Build Naive Bayes from scratch in Python: word counts, Laplace smoothing, log probabilities, a spam filter and Gaussian Naive Bayes, checked with scikit-learn.

By theprogrammers team · · 20 min read

Every SMS you receive from an unknown number passes through a filter that decides in a few milliseconds whether it's spam. Some of the first spam filters ever built, in the late 1990s, used Naive Bayes, and it's still a hard baseline to beat on short texts. It's also one of the easiest algorithms to build yourself: training is counting, and predicting is multiplying (or rather, adding logs).

In this lesson you'll write Naive Bayes from scratch in Python, twice:

  1. Multinomial Naive Bayes for text. You'll count words, add Laplace smoothing, see why the maths must be done with logarithms, work out one prediction by hand, and then train your class on 5,574 real SMS messages and check it against scikit-learn's MultinomialNB.
  2. Gaussian Naive Bayes for numbers. You'll fit a bell curve per feature and class, then classify penguin species from body measurements and check against GaussianNB.

What you need first: Naive Bayes explained and probability for machine learning. Comfort with NumPy arrays helps.

Key terms

  • Prior: how common a class is before you look at the message, such as P(spam) = 0.13.
  • Likelihood: how probable the evidence is if the class is true, such as P("free" | spam).
  • Posterior: the probability of the class after seeing the evidence, such as P(spam | "free lunch").
  • Vocabulary: the list of all distinct words in the training messages. Each word becomes one feature.
  • Laplace smoothing: adding a small count (usually 1) to every word, so no probability is ever exactly zero.
  • Log probability: the logarithm of a probability. Multiplying probabilities becomes adding logs, which avoids numbers too small for the computer to store.

The formula you'll implement

For a message with words w₁, w₂, …, Naive Bayes scores each class c as:

score(c) = P(c) × P(w₁ | c) × P(w₂ | c) × …

and predicts the class with the highest score. "Naive" means it treats every word as independent of the others, which is why the likelihood is a simple product. The proper posterior P(c | words) is each score divided by the sum of all the scores, so the posteriors add up to 1.

Training means estimating two things from the data:

WhatEstimateExample
P(c)messages of class c ÷ all messages3 spam out of 6 → 0.5
P(w | c)(count of w in class c + α) ÷ (all words in class c + α × vocabulary size)("free" 3 + 1) ÷ (11 + 1 × 14)

α (alpha) is the Laplace smoothing count, 1 by default.

Part 1: Multinomial Naive Bayes for text

Step 1: turn messages into word counts

The six messages from Naive Bayes explained. Build the vocabulary and the count table yourself, without scikit-learn:

import numpy as np

messages = ["win free money now", "free prize win", "claim your free prize",
            "meeting at noon", "lunch tomorrow at noon", "project meeting notes"]
labels = np.array(["spam", "spam", "spam", "ham", "ham", "ham"])

def tokenize(text):
    return text.lower().split()

vocabulary = sorted({word for message in messages for word in tokenize(message)})
word_index = {word: i for i, word in enumerate(vocabulary)}

def count_words(texts):
    counts = np.zeros((len(texts), len(vocabulary)), dtype=int)
    for row, text in enumerate(texts):
        for word in tokenize(text):
            if word in word_index:                  # words never seen in training are ignored
                counts[row, word_index[word]] += 1
    return counts

X_counts = count_words(messages)
print(len(vocabulary), "words:", vocabulary)
print(X_counts)
14 words: ['at', 'claim', 'free', 'lunch', 'meeting', 'money', 'noon', 'notes', 'now', 'prize', 'project', 'tomorrow', 'win', 'your']
[[0 0 1 0 0 1 0 0 1 0 0 0 1 0]
 [0 0 1 0 0 0 0 0 0 1 0 0 1 0]
 [0 1 1 0 0 0 0 0 0 1 0 0 0 1]
 [1 0 0 0 1 0 1 0 0 0 0 0 0 0]
 [1 0 0 1 0 0 1 0 0 0 0 1 0 0]
 [0 0 0 0 1 0 0 1 0 0 1 0 0 0]]

Each row is a message and each column is a word: the first row has a 1 under "free", "money", "now" and "win". This table is what scikit-learn's CountVectorizer builds. It's called a bag of words, because the order of the words is thrown away.

Step 2: priors and smoothed word probabilities

classes = np.unique(labels)                       # ['ham', 'spam'], in alphabetical order
alpha = 1.0

priors = np.array([np.mean(labels == c) for c in classes])
word_counts = np.array([X_counts[labels == c].sum(axis=0) for c in classes])     # shape (2, 14)
word_probs = (word_counts + alpha) / (word_counts.sum(axis=1, keepdims=True) + alpha * len(vocabulary))

for c, prior, total in zip(classes, priors, word_counts.sum(axis=1)):
    print(f"{c}: prior {prior}, {total} words")
for word in ["free", "lunch", "noon"]:
    i = word_index[word]
    print(f"{word:6} count ham {word_counts[0, i]}, spam {word_counts[1, i]}  "
          f"->  P(word | ham) {word_probs[0, i]:.4f}, P(word | spam) {word_probs[1, i]:.4f}")
print("each row of word_probs adds up to:", word_probs.sum(axis=1))
ham: prior 0.5, 10 words
spam: prior 0.5, 11 words
free   count ham 0, spam 3  ->  P(word | ham) 0.0417, P(word | spam) 0.1600
lunch  count ham 1, spam 0  ->  P(word | ham) 0.0833, P(word | spam) 0.0400
noon   count ham 2, spam 0  ->  P(word | ham) 0.1250, P(word | spam) 0.0400
each row of word_probs adds up to: [1. 1.]

Spam and ham have 3 messages each, so both priors are 0.5. "free" appears 3 times in the 11 spam words, so P("free" | spam) = (3 + 1) ÷ (11 + 14) = 4 ÷ 25 = 0.16. It never appears in ham, but thanks to smoothing it still gets (0 + 1) ÷ (10 + 14) = 0.0417 instead of 0. Each row of probabilities adds up to 1, as it should: every word in a class has to be one of the 14 vocabulary words.

Step 3: classify "free lunch" by hand

Multiply the prior by the probability of each word in the message, for each class:

new_message = "free lunch"
ham_score = priors[0] * word_probs[0, word_index["free"]] * word_probs[0, word_index["lunch"]]
spam_score = priors[1] * word_probs[1, word_index["free"]] * word_probs[1, word_index["lunch"]]
print(f"score(ham)  = 0.5 × {word_probs[0, word_index['free']]:.4f} × {word_probs[0, word_index['lunch']]:.4f} = {ham_score:.5f}")
print(f"score(spam) = 0.5 × {word_probs[1, word_index['free']]:.4f} × {word_probs[1, word_index['lunch']]:.4f} = {spam_score:.5f}")
total = ham_score + spam_score
print(f"P(ham | message) = {ham_score / total:.3f}, P(spam | message) = {spam_score / total:.3f}")
score(ham)  = 0.5 × 0.0417 × 0.0833 = 0.00174
score(spam) = 0.5 × 0.1600 × 0.0400 = 0.00320
P(ham | message) = 0.352, P(spam | message) = 0.648

"free" points strongly to spam (0.16 against 0.0417) and "lunch" points to ham (0.0833 against 0.04). "free" is the stronger clue, so spam wins: 0.00320 against 0.00174. Dividing by the total gives P(spam | "free lunch") = 0.648. That's the 0.65 scikit-learn printed in Naive Bayes explained, worked out by hand.

Step 4: why you must use logarithms

A real message has dozens of words, and each word probability is small. Multiply a few hundred of them and the result is smaller than the smallest number a computer can store:

p = 0.001
print("200 words:", p ** 200)
print("sum of 200 logs:", 200 * np.log(p))
200 words: 0.0
sum of 200 logs: -1381.5510557964274

0.001 multiplied by itself 200 times is 10⁻⁶⁰⁰, far below the smallest number a computer can store (about 10⁻³⁰⁸), so Python returns exactly 0.0. Every class would score 0 and the model couldn't choose. The sum of the logs, −1381.6, is an ordinary number.

So every real implementation works with log probabilities. Because log(a × b) = log(a) + log(b), the score becomes a sum:

log score(c) = log P(c) + Σ count(w) × log P(w | c)

With the count table, that's one matrix multiplication for all messages and classes at once: counts @ log_word_probs.T. A word that appears twice adds its log probability twice, which is why the count matters.

To turn log scores back into probabilities that add up to 1, subtract the largest log score before taking the exponent (this keeps the numbers in a safe range), then divide by the total. This is the same softmax trick as in logistic regression from scratch.

Step 5: the class

class MultinomialNaiveBayes:
    """Naive Bayes for count features such as word counts."""

    def __init__(self, alpha=1.0):
        self.alpha = alpha

    def fit(self, X, y):
        y = np.asarray(y)
        self.classes_ = np.unique(y)
        # total count of each word in each class; asarray/ravel also handles sparse matrices
        counts = np.vstack([np.asarray(X[y == c].sum(axis=0)).ravel() for c in self.classes_])
        smoothed = counts + self.alpha
        self.log_word_probs_ = np.log(smoothed / smoothed.sum(axis=1, keepdims=True))
        self.log_priors_ = np.log([np.mean(y == c) for c in self.classes_])
        return self

    def joint_log_scores(self, X):
        return X @ self.log_word_probs_.T + self.log_priors_

    def predict_proba(self, X):
        scores = self.joint_log_scores(X)
        scores -= scores.max(axis=1, keepdims=True)         # for numerical safety
        probs = np.exp(scores)
        return probs / probs.sum(axis=1, keepdims=True)

    def predict(self, X):
        return self.classes_[np.argmax(self.joint_log_scores(X), axis=1)]

Two details. X[y == c] picks the messages of one class, and .sum(axis=0) adds up each word's count. smoothed.sum(axis=1) already includes the α added to every word, so it equals "all words in the class + α × vocabulary size" from the formula. Test it on the six messages:

ours = MultinomialNaiveBayes().fit(X_counts, labels)
tests = ["free lunch", "win a prize now", "notes from the meeting"]
print(ours.predict(count_words(tests)))
print(ours.predict_proba(count_words(tests)).round(2))
['spam' 'spam' 'ham']
[[0.35 0.65]
 [0.06 0.94]
 [0.87 0.13]]

The same predictions and probabilities as scikit-learn's MultinomialNB in the theory lesson: "free lunch" is 0.65 spam, "win a prize now" 0.94 spam ("a" isn't in the vocabulary, so it's ignored), and "notes from the meeting" 0.87 ham.

Step 6: train it on 5,574 real SMS messages

The SMS Spam Collection is the dataset from the spam classifier project. Download it once, then split it:

Download the data: sms-spam.csv (487 KB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("sms-spam.csv").

import csv
import zipfile
import urllib.request
from pathlib import Path
import pandas as pd
from sklearn.model_selection import train_test_split

url = "https://archive.ics.uci.edu/static/public/228/sms+spam+collection.zip"
path = Path("sms_spam.zip")
if not path.exists():
    urllib.request.urlretrieve(url, path)
with zipfile.ZipFile(path) as z:
    sms = pd.read_csv(z.open("SMSSpamCollection"), sep="\t", header=None,
                      names=["label", "text"], quoting=csv.QUOTE_NONE)

train_text, test_text, y_train, y_test = train_test_split(
    sms["text"], sms["label"], test_size=0.25, stratify=sms["label"], random_state=0)
print(len(train_text), "training and", len(test_text), "test messages")
print(f"spam share: {(y_train == 'spam').mean():.3f}")
4180 training and 1394 test messages
spam share: 0.134

For thousands of messages, use scikit-learn's CountVectorizer to build the count table. It does what count_words does, but faster, and it also removes punctuation. Its output is a sparse matrix, which stores only the non-zero counts. Our class works with it unchanged: selecting rows, .sum(axis=0) and @ all work on sparse matrices too.

from sklearn.feature_extraction.text import CountVectorizer

vectorizer = CountVectorizer()
X_train = vectorizer.fit_transform(train_text)
X_test = vectorizer.transform(test_text)
print("vocabulary size:", len(vectorizer.vocabulary_))
print(f"non-zero counts: {X_train.nnz:,} of {X_train.shape[0] * X_train.shape[1]:,}")

ours = MultinomialNaiveBayes(alpha=1.0).fit(X_train, y_train)
our_predictions = ours.predict(X_test)
print(f"our test accuracy: {np.mean(our_predictions == y_test):.4f}")
vocabulary size: 7431
non-zero counts: 55,610 of 31,061,580
our test accuracy: 0.9842

Your class, about 30 lines of NumPy, classifies 98.42% of the 1,394 test messages correctly. The vocabulary has 7,431 words, but each message uses only a handful of them: only 55,610 of the 31 million cells in the count table are non-zero, which is why the sparse matrix matters.

Step 7: check against scikit-learn

from sklearn.naive_bayes import MultinomialNB

sk_nb = MultinomialNB(alpha=1.0).fit(X_train, y_train)
print(f"scikit-learn accuracy: {sk_nb.score(X_test, y_test):.4f}")
print("same predictions:", np.array_equal(our_predictions, sk_nb.predict(X_test)))
print(f"largest probability difference: {np.abs(ours.predict_proba(X_test) - sk_nb.predict_proba(X_test)).max():.2e}")
scikit-learn accuracy: 0.9842
same predictions: True
largest probability difference: 1.77e-14

Exactly the same accuracy, the same prediction for every one of the 1,394 messages, and probabilities that differ by at most 0.00000000000002, which is just rounding in the last decimal places. Your implementation is the real thing.

Step 8: which words say "spam"?

The ratio P(word | spam) ÷ P(word | ham) says how much more typical a word is of spam. Its log is simply the difference of the two log probabilities:

words = vectorizer.get_feature_names_out()
spam_vs_ham = ours.log_word_probs_[1] - ours.log_word_probs_[0]
order = np.argsort(spam_vs_ham)
print("most spam-like:", list(words[order[-10:]][::-1]))
print("most ham-like: ", list(words[order[:10]]))
most spam-like: ['claim', 'prize', '150p', 'tone', 'www', '500', '18', 'guaranteed', 'awarded', 'cs']
most ham-like:  ['gt', 'lt', 'he', 'lor', 'she', 'da', 'later', 'much', 'doing', 'said']

The spam words are what you'd expect: "claim", "prize", "guaranteed", "awarded", prices such as "150p" (pence per message) and "500", "www" and "18" (from "18+" age warnings). The ham words are everyday chat: "he", "she", "later", "lor" and "da" (Singapore and Indian English slang, since many messages came from Singapore). "gt" and "lt" come from < and > codes left in the original messages where numbers were removed: they're a quirk of how this dataset was collected, and the model happily uses them.

Part 2: Gaussian Naive Bayes for numbers

Word counts suit the multinomial version. For measurements such as lengths and weights, Gaussian Naive Bayes assumes that within each class, each feature follows a normal distribution (a bell curve). Training is just computing a mean and a variance for every feature in every class.

The probability density of a normal distribution with mean μ and variance σ² at the value x is:

f(x) = 1 / √(2πσ²) × e^(−(x − μ)² / (2σ²))

and its log, which is what you'll add up, is:

log f(x) = −½ log(2πσ²) − (x − μ)² / (2σ²)

Step 9: one feature, two species

Flipper length for Adelie and Gentoo penguins, with the bell curve fitted to each species:

Download the data: penguins.csv (15 KB), or from the original source, the palmerpenguins project. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("penguins.csv").

import seaborn as sns
import matplotlib.pyplot as plt

penguins = sns.load_dataset("penguins").dropna(subset=["bill_length_mm"]).reset_index(drop=True)
measurements = ["bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g"]

def log_normal_density(x, mean, var):
    return -0.5 * np.log(2 * np.pi * var) - (x - mean) ** 2 / (2 * var)

fig, ax = plt.subplots(figsize=(8, 4.5))
xs = np.linspace(165, 240, 300)
for species, colour in [("Adelie", "#c2410c"), ("Gentoo", "#0f766e")]:
    values = penguins.loc[penguins["species"] == species, "flipper_length_mm"]
    mean, var = values.mean(), values.var(ddof=0)
    print(f"{species}: mean {mean:.1f} mm, standard deviation {np.sqrt(var):.1f} mm")
    ax.hist(values, bins=20, density=True, alpha=0.35, color=colour)
    ax.plot(xs, np.exp(log_normal_density(xs, mean, var)), color=colour, linewidth=2, label=f"{species} (fitted normal curve)")
ax.axvline(206, color="grey", linestyle="--")
ax.set_xlabel("Flipper length (mm)")
ax.set_ylabel("Density")
ax.set_title("Gaussian Naive Bayes fits one bell curve per class and feature")
ax.legend()
plt.show()

for species in ["Adelie", "Gentoo"]:
    values = penguins.loc[penguins["species"] == species, "flipper_length_mm"]
    print(f"log density of 206 mm for {species}: {log_normal_density(206, values.mean(), values.var(ddof=0)):.2f}")
Adelie: mean 190.0 mm, standard deviation 6.5 mm
Gentoo: mean 217.2 mm, standard deviation 6.5 mm
log density of 206 mm for Adelie: -5.82
log density of 206 mm for Gentoo: -4.28
Histograms of flipper length for Adelie penguins, in orange, centred near 190 mm, and Gentoo penguins, in teal, centred near 217 mm, each with a smooth bell curve drawn over it. The two curves barely overlap. A dashed grey line marks 206 mm, where the orange curve is very low and the teal curve is somewhat higher.

The fitted curves follow the histograms well, so the normal assumption is reasonable here. At 206 mm, the Gentoo curve is higher (log density −4.28 against −5.82), so with equal priors this feature alone would say Gentoo. Gaussian Naive Bayes does this for every feature, adds the log densities and the log prior, and compares the totals.

Step 10: the Gaussian class

class GaussianNaiveBayes:
    """Naive Bayes for numeric features, with one normal distribution per feature and class."""

    def __init__(self, var_smoothing=1e-9):
        self.var_smoothing = var_smoothing

    def fit(self, X, y):
        X, y = np.asarray(X, dtype=float), np.asarray(y)
        self.classes_ = np.unique(y)
        self.means_ = np.array([X[y == c].mean(axis=0) for c in self.classes_])
        extra = self.var_smoothing * X.var(axis=0).max()       # keeps variances above zero
        self.vars_ = np.array([X[y == c].var(axis=0) for c in self.classes_]) + extra
        self.log_priors_ = np.log([np.mean(y == c) for c in self.classes_])
        return self

    def joint_log_scores(self, X):
        X = np.asarray(X, dtype=float)
        scores = []
        for mean, var, log_prior in zip(self.means_, self.vars_, self.log_priors_):
            scores.append(log_prior + log_normal_density(X, mean, var).sum(axis=1))
        return np.array(scores).T                                # shape (rows, classes)

    def predict_proba(self, X):
        scores = self.joint_log_scores(X)
        scores -= scores.max(axis=1, keepdims=True)
        probs = np.exp(scores)
        return probs / probs.sum(axis=1, keepdims=True)

    def predict(self, X):
        return self.classes_[np.argmax(self.joint_log_scores(X), axis=1)]

log_normal_density(X, mean, var) works on the whole table at once: mean and var have one value per feature, and NumPy broadcasts them across the rows. Summing across features is the "naive" product of the likelihoods, done in logs. var_smoothing adds a tiny amount to every variance, as scikit-learn does, so a feature that happens to be constant within a class doesn't cause a division by zero.

Step 11: classify penguins and check against scikit-learn

from sklearn.naive_bayes import GaussianNB

X = penguins[measurements].to_numpy()
y = penguins["species"].to_numpy()
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)

ours_g = GaussianNaiveBayes().fit(X_tr, y_tr)
sk_g = GaussianNB().fit(X_tr, y_tr)
print(f"our accuracy:          {np.mean(ours_g.predict(X_te) == y_te):.3f}")
print(f"scikit-learn accuracy: {sk_g.score(X_te, y_te):.3f}")
print("same predictions:", np.array_equal(ours_g.predict(X_te), sk_g.predict(X_te)))
print(f"largest mean difference: {np.abs(ours_g.means_ - sk_g.theta_).max():.2e}")
print(f"largest variance difference: {np.abs(ours_g.vars_ - sk_g.var_).max():.2e}")
our accuracy:          0.965
scikit-learn accuracy: 0.965
same predictions: True
largest mean difference: 0.00e+00
largest variance difference: 0.00e+00

Your class and GaussianNB agree exactly: the same 96.5% test accuracy, the same predictions, and identical means and variances. That's a little below KNN's 97.7% on the same split in the penguin project.

No scaling was needed. Each feature gets its own bell curve, measured in its own units, so grams and millimetres never get added together the way they do in a KNN distance.

Step 12: the shape of the decision boundary

With two features you can see what the model learns. Each class is an oval-shaped "hill" of probability, and the boundary is where two hills are equally high:

from sklearn.inspection import DecisionBoundaryDisplay
from matplotlib.colors import ListedColormap

pair = ["bill_length_mm", "bill_depth_mm"]
codes = {"Adelie": 0, "Chinstrap": 1, "Gentoo": 2}
X_pair = penguins[pair].to_numpy()
y_codes = penguins["species"].map(codes).to_numpy()
two_feature_nb = GaussianNaiveBayes().fit(X_pair, y_codes)

fig, ax = plt.subplots(figsize=(8, 5.5))
DecisionBoundaryDisplay.from_estimator(
    GaussianNB().fit(X_pair, y_codes), X_pair, response_method="predict",
    cmap=ListedColormap(["#fed7aa", "#ddd6fe", "#99f6e4"]), ax=ax)
for species, code in codes.items():
    points = X_pair[y_codes == code]
    ax.scatter(points[:, 0], points[:, 1], s=18, edgecolor="k", linewidth=0.3,
               color=["#c2410c", "#7c3aed", "#0f766e"][code], label=species)
ax.set_xlabel("Bill length (mm)")
ax.set_ylabel("Bill depth (mm)")
ax.set_title("Gaussian Naive Bayes: smooth, curved boundaries")
ax.legend()
plt.show()
print(f"training accuracy with 2 features: {np.mean(two_feature_nb.predict(X_pair) == y_codes):.3f}")
training accuracy with 2 features: 0.933
The bill length and bill depth scatter plot of all 342 penguins, with the background coloured by the species Gaussian Naive Bayes predicts: pale orange for Adelie at the left, pale purple for Chinstrap at the top right and pale teal for Gentoo at the bottom right. The borders between the regions are smooth and almost straight, without the small bumps and islands of a KNN boundary.

With only bill length and depth, it gets 93.3% right even on the penguins it learned from, which flatters a model. KNN with the same two features scored 96.9% in cross-validation, on penguins it hadn't seen. Look at the clouds in the chart: within each species, penguins with longer bills also have deeper bills, so each cloud is tilted. Naive Bayes assumes the two features are independent within a species, so it can only describe each species as an upright oval, not a tilted one. That's the "naive" assumption, visible in a picture: it costs some accuracy whenever features within a class are correlated.

Common mistakes

  • Multiplying probabilities directly. With more than a few dozen words the product becomes 0.0. Always add log probabilities.
  • Forgetting smoothing. One word unseen in a class gives that class a probability of 0, whatever the rest of the message says.
  • Building the vocabulary from all the data. Fit CountVectorizer on the training messages only, as in Step 6. Words that appear only in the test set must be ignored, just as they would be for genuinely new messages.
  • Trusting the probabilities too much. Because the independence assumption is false, Naive Bayes probabilities are usually pushed too close to 0 or 1. Use them to rank or classify, not as exact chances.
  • Using Gaussian Naive Bayes on counts or very skewed data. Bell curves don't fit word counts or values like income; use the multinomial version for counts, or transform skewed features first.

When to use Naive Bayes

Your data and problemNaive Bayes?Why
Short texts: SMS, emails, reviews, support ticketsYes, an excellent baselineTrains in milliseconds, works with little data and thousands of word features
Very little training dataYesNeeds only counts or means per class
Data that arrives continuouslyYesUpdate the counts with each new example (partial_fit in scikit-learn)
Numeric features with roughly bell-shaped classesYes, as a quick baselineGaussian Naive Bayes, no scaling needed
You need well-calibrated probabilitiesNoProbabilities are over-confident; use logistic regression
Features interact strongly ("A and B together mean spam")NoIt can't learn combinations; use trees or gradient boosting
Large tables of mixed numeric dataUsually noRandom forest or gradient boosting are usually more accurate

In the spam classifier project you'll compare Naive Bayes with logistic regression and a linear SVM on the same SMS data.

Practice

  1. By hand: with α = 1, what's P("money" | ham) for the six messages? "money" never appears in ham, ham has 10 words, and the vocabulary has 14.
Show the answer

(0 + 1) ÷ (10 + 1 × 14) = 1 ÷ 24 = 0.0417. Check: word_probs[0, word_index["money"]].

print(round(word_probs[0, word_index["money"]], 4))
0.0417
  1. Classify "claim your free money now" with your MultinomialNaiveBayes trained on the six messages. How sure is it?
Show the answer
six = MultinomialNaiveBayes().fit(X_counts, labels)
print(six.predict(count_words(["claim your free money now"])), six.predict_proba(count_words(["claim your free money now"])).round(3))
['spam'] [[0.019 0.981]]

Spam, with probability 0.981. "claim", "free", "money" and "now" all appear only in the spam messages, and "your" too, so every word pushes towards spam.

  1. Retrain on the SMS data with α = 0.1 and α = 10. What happens to test accuracy?
Show the answer
for a in [0.1, 1.0, 10.0]:
    model = MultinomialNaiveBayes(alpha=a).fit(X_train, y_train)
    print(f"alpha {a:4}: accuracy {np.mean(model.predict(X_test) == y_test):.4f}")
alpha  0.1: accuracy 0.9857
alpha  1.0: accuracy 0.9842
alpha 10.0: accuracy 0.9534

α = 0.1 is slightly better (98.57%), and α = 10 clearly worse (95.34%). Heavy smoothing adds 10 imaginary counts to every word, which drowns out the real counts of rare but telling words, such as "150p". The default of 1 is a safe start, but α is worth tuning with cross-validation.

  1. Count how many test SMS messages your filter gets wrong, and print two spam messages it missed.
Show the answer
wrong = test_text[our_predictions != y_test]
print(len(wrong), "mistakes")
missed_spam = test_text[(our_predictions == "ham") & (y_test == "spam")]
for text in missed_spam.head(2):
    print("-", text)
22 mistakes
- Hi ya babe x u 4goten bout me?' scammers getting smart..Though this is a regular vodafone no, if you respond you get further prem rate msg/subscription. Other nos used also. Beware!
- LIFE has never been this much fun and great until you came in. You made it truly special for me. I won't forget you! enjoy @ one gbp/sms

22 of the 1,394 messages are wrong. The missed spam is the hard kind: chatty and personal ("Hi ya babe", "LIFE has never been this much fun"), using the same everyday words as real messages, with the spam signal hidden at the end ("one gbp/sms"). Word counts can't see that the warning is the important part.

Interview questions

How does Naive Bayes handle a word in a new message that never appeared in training?

It ignores it: the word isn't in the vocabulary, so it has no column and adds nothing to any class's score. Words that are in the vocabulary but never appeared with a particular class are handled by Laplace smoothing, which gives them a small non-zero probability instead of zero.

Why are log probabilities used in Naive Bayes?

Multiplying many small probabilities underflows to zero in floating-point arithmetic. Taking logs turns the product into a sum of moderate negative numbers, which is numerically stable and also faster. The class with the highest sum of logs is the same as the class with the highest product.

What is the time complexity of training Naive Bayes?

Linear in the size of the data: one pass to count words (or compute means and variances) per class, O(n × d) for n examples and d features, and with sparse text data only the non-zero entries are visited. That's why it trains so quickly even on millions of documents.

Key takeaways

  • Naive Bayes multiplies a class prior by the probability of each feature given the class, and predicts the class with the highest score.
  • Multinomial Naive Bayes for text is counting: words per class, plus Laplace smoothing so nothing gets probability zero.
  • Real implementations add log probabilities, because multiplying hundreds of small numbers underflows to 0.
  • Gaussian Naive Bayes fits one bell curve per feature and class and needs no scaling.
  • Both from-scratch classes matched scikit-learn exactly, on 1,394 SMS messages and on the penguins.

Frequently asked questions

Is Naive Bayes still used today?

Yes, especially as a fast baseline for text classification and wherever training must be cheap or data is scarce. Modern spam filters combine many signals and models, but Naive Bayes-style word statistics are still part of the toolbox.

What is the difference between Multinomial and Bernoulli Naive Bayes?

Multinomial uses how many times each word appears. Bernoulli only uses whether each word appears or not, and it also counts the absence of a word as evidence. Bernoulli can work better for very short texts; Multinomial is the usual choice.

Does Naive Bayes need feature scaling?

No. The multinomial version works on raw counts, and the Gaussian version models each feature separately in its own units, so changing the scale of a feature changes its mean and variance but not the predictions.

What to learn next

  1. Build a complete, evaluated spam filter in the spam classifier project.
  2. Revise the theory in Naive Bayes explained.
  3. Compare with another from-scratch build in logistic regression from scratch.