π Naive Bayes
Descriptionβ
< What is it? >β
- Meaning: Naive Bayes is a family of supervised classifiers that use Bayes' theorem to predict a class from observed features. Training estimates class frequencies and feature distributions; prediction combines that information to choose the most probable class.
- Why βnaiveβ: the model assumes features are conditionally independent given the class. For a spam classifier, it treats the presence of
freeandwinas independent once the spam/non-spam class is specified. This simplifies computation even though real words can be related. - Example: given an email containing
freeandwin, compare the scores forspamandnot_spam, then choose the larger one. The worked example below predictsspam.
Key pointsβ
< What is prior probability? >β
-
Meaning: a prior probability is the probability assigned to an event or class before considering the new evidence. In Naive Bayes classification, the class prior is the starting probability before inspecting the current input's features. βBeforeβ refers to this new input, not to all historical data: a prior can be estimated from previous observations.
-
Estimate from training labels: a common class-prior estimate is the fraction of training examples belonging to that class:
Here, is the number of training examples in class , and is the total number of training examples. See Stanford's Naive Bayes explanation.
-
Example: the six-email dataset below contains 3 spam and 3 non-spam emails. Before examining a new email's words, the model starts with and . After observing
freeandwin, it combines those priors with the feature likelihoods. The worked calculation gives a posterior spam probability of approximately 0.857.Prior: spam probability before inspecting this email = 0.50+ Evidence: this email contains "free" and "win"β Posterior: spam probability after using that evidence β 0.857The prior describes the starting class frequency; the posterior accounts for the particular email. The arrow represents a Bayesian update, not literal addition of probabilities.
-
Unequal class frequencies: if 20 out of 100 training emails are spam, the empirical spam prior is , not simply because there are two classes. Priors can also be specified using known population frequencies. A deliberately balanced training sample may not reflect the class proportions seen in production.
< How the classifier makes a prediction >β
-
Bayes' theorem: for a class and feature vector :
Term Meaning Prior: how common the class is before observing this input Likelihood: how probable the observed features are under that class Posterior: the class probability after observing the features Evidence: the normalizing term shared by all classes for this input -
Example β spam probability after seeing βfreeβ: suppose we examine 100 emails with the following counts. This illustrative dataset uses one feature to explain Bayes' theorem; the Implementation section uses a separate six-email dataset with two features.
Email type Contains βfreeβ Does not contain βfreeβ Total Spam 16 4 20 Not spam 8 72 80 Total 24 76 100 Let mean βspamβ and mean βcontains free.β Each probability comes directly from the counts:
Term Meaning in this example Value Probability an email is spam before checking its words β the prior Probability it contains βfree,β given that it is spam β the likelihood Probability any email contains βfreeβ β the evidence probability Probability it is spam, given that it contains βfreeβ β the posterior What we calculate Substitute these values:
Before reading the email, the spam probability was 20%. After seeing βfree,β it becomes about 66.7%. Verify this directly: 24 emails contain βfree,β and 16 of those are spam, so the probability is .
The direction matters: and answer different questions.
-
Independence assumption: replace the joint likelihood with a product of feature likelihoods. The shared denominator can be omitted when selecting the largest score:
See the scikit-learn Naive Bayes guide.
< Training, smoothing, and numerical stability >β
-
Training labels: provide examples with known classes, such as emails labeled
spamornot_spam. Standard Naive Bayes training estimates counts or distribution parameters; it does not require a neural network or backpropagation. -
Smoothing: add pseudocounts so an unseen feature value does not force a class likelihood to zero. For binary features, add-one smoothing estimates:
Here, counts class- examples where feature is present, and counts all class- examples. The denominator adds 2 because a binary feature has two outcomes. Absence contributes .
-
Log scores: implementations sum log probabilities rather than multiplying many tiny values, avoiding numerical underflow. See Stanford's Naive Bayes chapter.
Comparisonβ
< Naive Bayes vs. Decision Tree >β
-
Features and prediction: both models classify inputs represented as features. Decision trees classify by splitting on features, while Naive Bayes combines class priors with feature likelihoods. Bag of Words (BoW) turns text into features such as word counts; either model can use this representation. Naive Bayes can also use other feature types, such as continuous measurements with
GaussianNB. -
Practical starting point: try Naive Bayes for a fast text-classification baseline using word counts or word-presence features. Try a small decision tree for tabular classification when feature thresholds, combinations of conditions, and readable decision paths matter. These are starting points to evaluate, not guarantees that one model will win.
Consideration Naive Bayes Decision Tree How it predicts Combines class priors and feature likelihoods Follows learned feature splits to a leaf Useful starting tasks Spam filtering, document categories, support-ticket routing Tabular classification with threshold-based decisions Feature interactions Assumes conditional independence given the class; does not directly learn interactions Can learn interactions through successive splits Many sparse text features Multinomial and Bernoulli variants are natural baselines Can use them, but a single tree may need many splits Interpretability Inspect priors and feature evidence for each class A shallow tree provides an explicit if/else path Training and tuning Usually fast; choose the feature distribution and smoothing Control depth, minimum leaf size, or pruning to limit overfitting Main limitation Related features can count similar evidence repeatedly Deep trees can overfit; small data changes can change the tree See the scikit-learn guides for Naive Bayes and decision trees.
-
Example β spam classification: a Bag of Words representation could encode an email as
[count of "free", count of "win"]. Both models can use this vector: a decision tree might split oncount of "free" > 0, while Naive Bayes combines the likelihood of those counts under each class with its prior. For thousands of word-count features,MultinomialNBis a useful starting point; for binary word-presence features, tryBernoulliNB. -
Example β lipstick recommendations: in the Decision Tree example, gender, age, income, and nationality are tabular features. A tree can first split on gender, then use a different age or income threshold within a child. This makes conditional patterns visible. Naive Bayes can also classify tabular data, but its likelihood model must suit the features; mixing continuous and categorical fields requires appropriate handling.
-
How to decide: compare both on the same validation split using metrics appropriate to the task, such as precision, recall, and F1. Fit preprocessing only on training data. Inspect errors and evaluate probability calibration if probabilities drive decisions; neither model guarantees reliable probabilities. Choose the simpler model that meets the measured quality and runtime requirements.
< Common Naive Bayes variants >β
-
Choose the likelihood for the feature type: these variants share the classification principle but model inputs differently.
Variant Typical input Example Bernoulli Binary presence/absence Whether each vocabulary word occurs in an email Multinomial Nonnegative counts; often also used with TF-IDF Word occurrence counts Gaussian Continuous values, modeled as Gaussian within each class Numeric measurements Categorical Discrete category values Device type or subscription plan scikit-learn provides
BernoulliNB,MultinomialNB,GaussianNB, andCategoricalNBin its Naive Bayes module.
Implementationβ
< Classify an email with Bernoulli Naive Bayes >β
-
Training input: each email becomes two binary features:
[contains free, contains win]. This deliberately small dataset makes the calculations visible; repeated feature vectors can represent different emails.Email Contains freeContains winLabel 1 1 1 spam 2 1 0 spam 3 1 1 spam 4 0 0 not_spam 5 0 1 not_spam 6 0 0 not_spam -
Worked prediction: both classes have prior . After add-one smoothing:
Class Score for [1, 1]spam not_spam Normalize the scores to obtain the model's posterior:
The predicted label is spam. This toy probability is not a measured real-world accuracy.
-
Runnable Python: this standard-library implementation trains on the table and predicts
[1, 1]. It also handles absent features by using their complement probabilities.import math# Features: [contains "free", contains "win"].X = [[1, 1], [1, 0], [1, 1], [0, 0], [0, 1], [0, 0]]y = ["spam", "spam", "spam", "not_spam", "not_spam", "not_spam"]classes = ["spam", "not_spam"]model = {}# Training: estimate priors and smoothed feature probabilities.for label in classes:rows = [row for row, target in zip(X, y) if target == label]prior = len(rows) / len(X)probabilities = [(sum(row[j] for row in rows) + 1) / (len(rows) + 2)for j in range(len(X[0]))]model[label] = (prior, probabilities)# Inference: an email containing both words.query = [1, 1]log_scores = {}for label, (prior, probabilities) in model.items():log_scores[label] = math.log(prior) + sum(math.log(p if value == 1 else 1 - p)for value, p in zip(query, probabilities))# Normalize safely to posterior probabilities under the model.maximum = max(log_scores.values())weights = {label: math.exp(score - maximum)for label, score in log_scores.items()}total = sum(weights.values())for label in classes:print(f"{label}: {weights[label] / total:.3f}")print("prediction:", max(log_scores, key=log_scores.get)) -
Verified output:
spam: 0.857not_spam: 0.143prediction: spamFor a library implementation, use scikit-learn's BernoulliNB with
alpha=1.0on the same binary features.
Troubleshootβ
< What can make predictions misleading? >β
- Correlated features: several related features can count similar evidence repeatedly, producing overconfident probabilities. Assess calibration if probability quality matters.
- Wrong feature model: binary flags, counts, and continuous measurements require appropriate likelihoods. Do not assume every variant accepts the same representation.
- Evaluation: measure performance on held-out examples. A confusion matrix helps distinguish missed spam from legitimate emails incorrectly blocked. The six-row demonstration verifies arithmetic, not generalization.
Video Tutorialβ
- Naive Bayes, Clearly Explained !!!
- Naive Bayes Explained Visually
- Naive Bayes FROM SCRATCH in Python
Related ideasβ
- Classification predicts category labels.
- Search & Retrieval explains tokenization and text preprocessing.
- Term FrequencyβInverse Document Frequency (TF-IDF) represents text with weighted terms.
- Decision Tree classifies inputs through learned feature splits.
Referenceβ
- Naive Bayes (scikit-learn)
- BernoulliNB (scikit-learn)
- Naive Bayes text classification (Introduction to Information Retrieval)