Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Naive Bayes

Bayes Theorem

P(A∣B)=P(B∣A)⋅P(A)P(B)P(A|B) = \frac{P(B|A) \cdot P(A)}{P(B)}

Bayes’ Theorem:
Update your belief when you have new evidence.

TermMeaning
P(A)P(A)Prior. What you believed about A before seeing any evidence.
P(B∣A)P(B \mid A)Likelihood. How probable evidence B is, if A were true.
P(A∣B)P(A \mid B)Posterior. Updated belief about A after seeing evidence B.
P(B)P(B)Normalizer. Overall probability of seeing B regardless of A.
  • In classification,

    P(Y=k∣X=x)=πkfk(x)∑l=1Kπlfl(x)P(Y=k | X=x) = \frac{\pi_kf_k(x)}{\sum_{l=1}^K\pi_lf_l(x)}
  • P(Y=k∣X=x)P(Y=k|X=x): Posterior probability.

    • “Given I observed this data point xx, what is the probability that it belongs to class kk?”

    • We want to find out the class kk that maximizes this probability.

    • The goal is to predict class kk that maximizes the posterior probability: arg⁡max⁡k(πk∏j=1pfkj(xj))\arg\max_{k} \left( \pi_k \prod_{j=1}^{p} f_{kj}(x_j) \right)

    • Equation can be written this way because we can ignore the denominator as the denominator will be a constant.

  • πk\pi_k: Prior probability of class kk.

    • How common class kk is in the population before seeing any data.

    • If 70% of training data is labeled as class A, then πA=0.7\pi_\text{A} = 0.7.

  • fk(x)f_k(x): Likelihood.

    • fk(X)=P(X=x∣Y=k)f_k(X) = P(X=x|Y=k): Also called as conditional density.

    • Given that a point belongs to class kk, how probable is it to look like xx (how typical is this data point)?

    • For the Gaussian version, assume that the density is multivariate Gaussian with diagonal covariance. If class kk has a Gaussian distribution, fk(x)f_k(x) is just the Gaussian PDF evaluated at xx.

  • ∑l=1Kπlfl(x)\sum_{l=1}^{K} \pi_l f_l(x): Sums over all KK classes. Normalizing constant that ensures all postieror probabilities across classes sum to 1.

Assumption

  • We assume that conditional on class kk, variables xjx_j are independent. Hence we multiply the conditional density of each variable to get the joint density:

    fk(X)=∏j=1pfkj(xj)f_k(X) = \prod_{j=1}^{p} f_{kj}(x_j)
  • When combined with Bayes Theorem:

    P(Y=k∣X=x)=πkfk(x)∑l=1Kπlfl(x)=πk∏j=1pfkj(xj)∑l=1K(πl∏j=1pflj(xj))P(Y = k \mid X = x) = \frac{\pi_k f_k(x)}{\sum_{l=1}^{K} \pi_l f_l(x)} = \frac{\pi_k \prod_{j=1}^{p} f_{kj}(x_j)}{\sum_{l=1}^{K} \left( \pi_l \prod_{j=1}^{p} f_{lj}(x_j) \right)}
  • When XX has many features with pp-dimensions, estimating fk(x)f_k(x) as a full multivariate Gaussian is expensive and requires a lot of data. So in naive bayes, we pretend that all features are independent of each other within each class.

    • Hence, conditional on the outcome, there is no muilticollinearity.

    • Once you already know the class, Naive Bayes only requires the features to be independent.

    • x1x_1 and x2x_2 are independent given Y=kY=k.

P(x1,x2∣Y=k)=P(x1∣Y=k)×P(x2∣Y=k),P(x_1, x_2 | Y=k) = P(x_1 | Y=k) \times P(x_2|Y=k)\text{,}
where k is the same throughout.\text{where } k \text{ is the same throughout.}
  • When there are many features, multiplying lots of small number together to achieve fk(X)=∏j=1pfkj(xj)f_k(X) = \prod_{j=1}^{p} f_{kj}(x_j) causes numerical underflow; product becomes so small that gets rounded up to zero and everything beraks.

    • This problem can be avoided by taking log transformation and turn product into a sum.

      logfk(x)=∑j=1plog⁡fkj(xj)\text{log} f_k(x) = \sum^p_{j=1} \log f_{kj}(x_j)
    • Because log function is monotone, taking the log does not change the class kk that yields the maximum posterior probability.

Conditional independence is within a class

Two features can be associated in the full sample even when they are independent within each class. For example, two words may both occur more often in one document class. Their overall association can come from the mixture of classes.

The assumption is stronger than zero correlation: knowing one feature must give no additional information about another after conditioning on the class. It is a modeling assumption, not something that preprocessing automatically makes true. Duplicate features count the same evidence twice and can make the posterior too extreme.

For classification, use the log score

sk(x)=log⁡πk+∑j=1plog⁡fkj(xj).s_k(x)=\log\pi_k+\sum_{j=1}^p\log f_{kj}(x_j).

The prior must remain in this score. Only the denominator shared by all classes can be dropped when choosing the largest score.

Definition of Density
  • Instead of using probabilities of an event happening as in discrete variables, for continous variables, probability over an interval is stated instead.

  • Density function, f(x)f(x), describes how concentrated the probability is around each value of xx.

    P(a≤x≤b)=∫abf(x) dxP(a \leq x \leq b) = \int_a^b f(x) \, dx

Estimation

  • Estimation means computing the parameters of a model from training data since we don’t know the true values.

  • In Naive Bayes, estimate the prior probability from training data. Also called as proportional prior.

πk=nkn,\pi_k = \frac{n_k}{n}\text{,}
nk=Number of training points in class k, n=Total number of training pointsn_k = \text{Number of training points in class }k \text{, } n = \text{Total number of training points}
  • Called proportional because it’s just the proportion of each class in the training data.

Categorical Variable

  • If the xx-variable is categorical, density is a probability.

fkj(xj)=P(Xj=x∣Y=k)=nkjnk,f_{kj}(x_j) = P(X_j=x|Y=k) = \frac{n_{kj}}{n_k}\text{,}
nk=Number of observations in class k, n_k = \text{Number of observations in class }k \text{, }
nkj=The number of observations in class k taking the value xjn_{kj} = \text{The number of observations in class }k \text{ taking the value } x_{j}

Continuous Variable

  • Estimate probability from a marginal density.

    fkj(xj)=12πσjk2exp⁡[−12(xj−μjkσjk)2]f_{kj}(x_j) = \frac{1}{\sqrt{2\pi\sigma_{jk}^2}} \exp\left[-\frac{1}{2}\left(\frac{x_j - \mu_{jk}}{\sigma_{jk}}\right)^2\right]
  • Typically, Gaussian distribution is assumed. In this case, it is called as Gaussian Naive Bayes.

LaPlace Smoothing

Zero Probability Problem

When you estimate probabilities from training data using nkjnk\frac{n_{kj}}{n_k}, you often get a probability of 0 if a particular feature never appears in class kk.

P(X=some value∣Y=k)=0nk=0P(X=\text{some value}|Y=k) = \frac{0}{n_k} = 0

And since Naive bayes multiplies all features’ probabilities together,

πk∏j=1pfkj(xj)=πk×...×0×...=0\pi_k \prod^p_{j=1} f_{kj}(x_j) = \pi_k \times ... \times 0 \times ... = 0

So, one single 0 can wipe out the entire product and ignore evidence from all other features.

Intuition

LaPlace smoothing adds a small count (usually 1) to every possible value, pretending that there is at leaset one count.

P(X=u∣Y=k)=nkj+1nk+VP(X=u|Y=k) = \frac{n_{kj}+1}{n_k+V}
V= Number of possible values the feature can take.V=\text{ Number of possible values the feature can take.}
  • VV refers to the number of catgories of the corresponding xx-variable.

  • Data above gets transformed to:

compliantindependentchain
no3+10+1
yes7+15+1
compliantSan MateoLos AngelesSan FranciscoContra CostaMarin
no1+12+10+10+10+1
yes1+18+11+11+11+1
  • For county, add dj=5d_j = 5 for each yy category (in the denominator).

Generalized LaPlace Estimator

  • Instead of adding 1 count, we can add an arbitrary number of observations, LL, that controls the amount of shrinking.

    P(Xj=xj∣Y=k)=nkj+Lnk+L∗djP(X_j = x_j \mid Y = k) = \frac{n_{kj} + L}{n_k + L * d_j}
  • If LL is very large, it gets summarized to P(Xj=xj∣Y=k)=1djP(X_j = x_j \mid Y = k) = \frac{1}{d_j}.

  • LL can be choosen by minimizing error on validation data.

  • LL does not have to be an integer value.

Choosing the feature distribution

  • Gaussian Naive Bayes models a continuous feature with a class-specific mean and variance. The density value is not the probability of observing one exact real number.

  • Bernoulli Naive Bayes models binary presence or absence. Absence contributes to the likelihood as well as presence.

  • Multinomial Naive Bayes models token counts within a document. Repeated words contribute repeatedly, and smoothing uses total token counts in the class as the denominator base, rather than the number of documents.

The categorical smoothing formula above applies to one categorical feature at a time. Adding LL to each of its djd_j categories adds LdjLd_j to the denominator, keeping the probabilities summed to 1.

Class priors also matter. If training observations were deliberately balanced by sampling equal numbers from each class, the sample proportions may not represent the population where predictions will be made. Interpret posterior probabilities with that sampling scheme in mind.

Usage

  • When a fast algorithm is needed.

    • Naive Bayes transforms multivariate problems into univariate by looking at each feature separately, and computes fkj(xj)f_{kj}(x_j) for each individually. Does not look at features jointly.

    • Both training and test data complexity are linear in size of data.

    • Hence, useful for high dimensional data with text classifications.

  • When there is only small training data available.

    • Because we are estimating simple univariate distribute per feature per class.

  • When features are genuinely mostly independent.

Limitations

  • When features are strongly correlated.

  • When feature interactions matter for decision.

  • When we need a well-calibrated probabilities.

    • Naive Bayes posterior probabilities are often overconfident due to the independence assumption.