Knowledge / Artificial Intelligence and Data Science / Naive Bayes and probabilistic models

Naive Bayes and probabilistic models

Artificial Intelligence and Data Science (B.E./B.Tech) · Machine learning · free study notes for exams, placements and interviews

In short

Naive Bayes is a family of classifiers that apply Bayes' theorem to turn class priors and per-feature likelihoods into a posterior probability for each class, under the simplifying ("naive") assumption that features are conditionally independent given the class. It is the cheapest serious classifier available: training is a single pass of counting, prediction is a sum of logarithms, and it stays usable with thousands of features and only hundreds of labelled rows. Probabilistic modelling also supplies the vocabulary — prior, likelihood, posterior, MLE, MAP, Bayes risk — used across the rest of machine learning. In Indian exams it is standard in AICTE/CBCS machine-learning papers and in GATE (CS and the Data Science & AI paper), usually as a numerical question on a small table or a text corpus. In interviews at TCS, Infosys, Wipro, Zoho, Freshworks, Flipkart, Paytm and the analytics arms of HDFC/ICICI, it appears as spam filtering, sentiment tagging, ticket routing and "explain Bayes' theorem on a test with 1% prevalence".

Explained

Probability foundations and Bayes' theorem

The Bayes classifier, decision rule and risk

The naive conditional-independence assumption

Variants and when to use each

VariantFeature typeLikelihood usedTypical use
Gaussian NBContinuousNormal density per class per featureSensor, biometric, CGPA/marks data
Multinomial NBCounts / frequenciesMultinomial over vocabularyDocument classification, bag-of-words, TF-IDF
Bernoulli NBBinary presence/absencepx (1−p)1−x, includes absent termsShort text, SMS spam, tag prediction
Categorical NBNominal categoriesPer-category probability tableWeather/credit tables in exam questions
Complement NBCounts, imbalancedStatistics of the *complement* of each classSkewed text corpora

Training, smoothing and numerical practice

  1. Estimate priors by counting: P̂(C_k) = N_k / N.
  2. For each class and feature, estimate the likelihood parameters — category proportions, word-count proportions, or (mean, variance) for Gaussian NB. These are the closed-form MLE values; there is no iterative optimisation and no learning rate.
  3. At prediction, compute a log score per class, pick the maximum, and normalise with softmax/log-sum-exp if a probability is required.
  4. Zero-frequency problem: one unseen category or word gives P̂ = 0, and the whole product collapses to 0 regardless of other evidence. Cure with additive (Laplace/Lidstone) smoothing: add α to every count (α = 1 is Laplace, α < 1 is Lidstone). Smoothing is exactly a Dirichlet prior, so the smoothed estimate is a MAP estimate.
  5. Underflow: multiplying thousands of small probabilities underflows float64. Always work with sums of natural logs; use the log-sum-exp trick for the normaliser.
  6. Unknown words at test time are simply dropped (or mapped to an UNK token) — they contribute the same constant to every class.
  7. Missing feature values are easy: omit that factor for that row, since the product factorises. Most algorithms cannot do this.
  8. Complexity: training O(N·d), prediction O(d·K) — one pass, trivially parallel, naturally online/incremental (update counts as data arrives).

Advantages, limitations and comparisons

Beyond naive Bayes — the probabilistic toolkit

Key points

Formulas and examples

Bayes' theorem: P(C|x) = P(x|C)·P(C) / P(x), where P(x) = Σ_k P(x|C_k)·P(C_k). All terms dimensionless probabilities in [0,1].
Naive Bayes classifier: ŷ = argmax_k P(C_k) · Π_{j=1..d} P(x_j | C_k) (d = number of features, K = number of classes)
Log form (used in practice): ŷ = argmax_k [ ln P(C_k) + Σ_j ln P(x_j | C_k) ]
Additive (Laplace) smoothing, categorical: P̂(x_j = v | C_k) = (N_{kjv} + α) / (N_k + α·V_j), α ≥ 0, V_j = number of distinct values of feature j
Multinomial NB: P̂(w_t | C_k) = (count(w_t, C_k) + α) / (Σ_{s=1..|V|} count(w_s, C_k) + α·|V|); P(d|C_k) ∝ Π_t P̂(w_t|C_k)^{f_t}, f_t = frequency of w_t in document d
Bernoulli NB: P(x | C_k) = Π_j p_{kj}^{x_j} (1 − p_{kj})^{(1 − x_j)}, x_j ∈ {0,1}
Gaussian NB: P(x_j | C_k) = (1 / √(2π σ_kj²)) · exp[ −(x_j − μ_kj)² / (2 σ_kj²) ], μ in feature units, σ² in units²
Two-class log-odds (linear form): ln[P(C₁|x)/P(C₂|x)] = ln[P(C₁)/P(C₂)] + Σ_j ln[P(x_j|C₁)/P(x_j|C₂)]
MLE vs MAP for a Bernoulli with Beta(α,β) prior: θ̂_MLE = k/n; θ̂_MAP = (k + α − 1)/(n + α + β − 2); posterior mean = (k + α)/(n + α + β)
Expected risk: R(i|x) = Σ_j L(i|j)·P(C_j|x); decide i minimising R. Log-sum-exp: ln Σ_k e^{s_k} = s_max + ln Σ_k e^{(s_k − s_max)}

Example 1 — base rates (the classic interview numerical). A screening test has sensitivity P(+|D) = 0.99 and specificity 0.95, so P(+|no D) = 0.05. Disease prevalence P(D) = 0.01. A random person tests positive — probability they have the disease?

Example 2 — categorical naive Bayes from a count table. Outdoor-practice dataset, 14 rows, Play = Yes in 9, No in 5.

Feature = valueYes (of 9)No (of 5)
Outlook = Sunny23
Outlook = Overcast40
Outlook = Rain32
Temp = Cool31
Humidity = High34
Wind = Strong33

Query x = (Sunny, Cool, High, Strong):

Example 3 — multinomial NB on text with Laplace smoothing. Vocabulary V = {loan, offer, interview, resume, campus}, |V| = 5. Training: 2 Spam docs with total word counts loan 4, offer 3, interview 1, resume 0, campus 0 (total 8); 3 Ham docs with loan 0, offer 1, interview 4, resume 3, campus 2 (total 10). Priors: P(Spam) = 2/5 = 0.4, P(Ham) = 3/5 = 0.6. Classify d = "loan offer interview" with α = 1.

Example 4 — Gaussian NB. Shortlisting model on one feature, CGPA. Shortlisted: μ = 8.4, σ = 0.5, prior 0.30. Not shortlisted: μ = 7.0, σ = 0.8, prior 0.70. Candidate has CGPA 7.8.

Example 5 — MLE vs MAP. A placement cell converts 3 offers out of 10 final interviews. Estimate the conversion rate θ.

from sklearn.naive_bayes import MultinomialNB, GaussianNB
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import make_pipeline

clf = make_pipeline(CountVectorizer(), MultinomialNB(alpha=1.0))  # alpha = Laplace
clf.fit(train_texts, train_labels)
proba = clf.predict_proba(test_texts)          # treat as scores, not calibrated probabilities
# GaussianNB(var_smoothing=1e-9) adds a floor to variances to avoid divide-by-zero

Where it is used

Interview questions

Common mistakes

Related topics

Linear and logistic regression · Model evaluation metrics · Overfitting, bias-variance and regularisation · Decision trees and random forests · Clustering: k-means and hierarchical · Anomaly detection

Open in the Knowledge reader →Find jobs →