Naive Bayes › Formula
Machine Learning from ScratchAll chapters Naive Bayes › FormulaSection view · Sections in this chapter4 / 10 ↓
Reading tools Definitions, links & notes
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
This section derives the Bayes decision rule and the log score, then develops the Gaussian and multinomial event models that the implementation uses.
Bayes decision rule and conditional independence
Every probabilistic classifier has to answer the same question: given a vector of measurements, which class is most plausible? Naive Bayes answers it by describing what data from each class look like, weighting those descriptions by how common each class is, and letting Bayes' theorem combine the two. The argument below builds that answer in stages: first the decision rule, then the obstacle that makes the rule impractical, then the assumption that removes the obstacle, and finally the numerical form a program evaluates.
We have a feature vector and a class label . Under equal-cost zero-one loss, the Bayes decision rule returns a class with the largest posterior probability , using a specified tie convention. Unequal error costs can require a different decision. Bayes' theorem expresses this posterior as
Each of the three factors has a distinct job:
- is the prior. It says how common class is before we look at any features at all.
- is the class-conditional likelihood. It says how plausible this particular measurement vector is if the class really is . This is where the model's description of the data lives.
- is the evidence. It is the marginal mass or density of the feature vector, with the class averaged out. It has no in it.
Only the first two factors carry information about which class we are in. The evidence can always be recovered afterwards by summing the numerator over classes:
Because that denominator is one number shared by every class, it rescales all posteriors by the same amount. Rescaling cannot change which class is largest, so the decision rule needs to look only at the numerator:
Here means the value of that makes the expression as large as possible. We are not yet comparing calibrated posterior probabilities; we are only asking which class produces the largest unnormalized score. The normalized probabilities come back later, and the ranking established here survives that normalization unchanged.
At this point the decision rule is settled, and the real difficulty becomes visible. The likelihood is a joint density over dimensions. Describing it without any structure means modelling how every feature varies with every other feature inside each class. For an unrestricted discrete joint table with possible values per feature, there are cells. Other structured families have different costs: a full Gaussian covariance, for example, has a quadratic rather than exponential parameter count. Naive Bayes reduces the feature model to class-conditional marginals.
The naive Bayes assumption is
This says that, conditional on the class, the features are independent. It does not imply that they are independent overall: mixing classes can create marginal association even when features are independent within every class. Within spam, the factorization says that seeing "free" supplies no further information about whether "win" appears once the class is known. Whether that holds depends on the class-specific data-generating process; Bayes' theorem alone does not supply the assumption. But it is far cheaper to estimate: the joint likelihood collapses from one complicated -dimensional object into a product of one-dimensional densities, and each of those can be estimated from a single column of the data.
Substituting the product into Bayes' theorem gives
where is the prior. The class score before normalization is
Taking logarithms is not cosmetic. Products of many small probability masses or densities can underflow floating-point arithmetic. A density can also exceed one, so very large density products can overflow. The logarithm is strictly increasing, so it does not change which class has the largest score. It converts the product into a sum, avoiding a direct product of small factors. The score still requires finite inputs and valid distribution parameters. It also exposes the structure of the model: each feature contributes one additive term, so a score can be decomposed into the prior plus a list of per-feature contributions that we can read off and interpret.
Once we have the scores, the normalized posterior is
For a batch of observations, we can store the scores in an matrix , where . Each column corresponds to a class, and each row corresponds to an observation. In code, we compute this matrix with broadcasting rather than writing nested loops.
One ingredient remains: the prior itself. It is usually estimated by its maximum likelihood value,
where is the number of training observations in class and is the total number of observations. If a class is rare, we may want to smooth the prior or set it explicitly. With Laplace smoothing, the estimate becomes
For , the extra pseudo-counts keep every prior strictly positive. This is the same idea we use for word probabilities later.
Gaussian and multinomial event models
The score above is a sum of terms of the form . Nothing in the derivation so far has said what that quantity is. Specifying it is choosing an event model, and the choice is where the modelling happens: it decides what kind of data the classifier can describe well. The two choices developed here are Gaussian for continuous features and multinomial for count features.
For Gaussian naive Bayes, we assume that feature within class follows a normal distribution:
where:
- : the value of feature for a given observation
- : the class label
- : the mean of feature within class
- : the variance of feature within class
- : the normal distribution with mean and variance
The density (probability density function) is
where:
- : the conditional density of feature given class
- : the mean of feature within class
- : the variance of feature within class
- : the constant
The factor normalizes the density so that it integrates to one. The exponent measures the squared distance between and the class mean, measured in units of the class standard deviation. A point far from the mean gets a small density. The variance controls how wide the distribution is: a large variance makes distant points less penalized.
When a class has observations with positive within-class variation for a feature, its Gaussian maximum likelihood estimates are the sample mean and the variance with divisor :
where:
- : the estimated mean of feature within class
- : the estimated variance of feature within class
- : the number of training observations in class
- : the value of feature for observation
- : the class label of observation , with the sum restricted to observations satisfying
With positive within-class variation, dividing by gives the variance MLE; for , dividing by gives the unbiased sample variance. If every value of the feature in a class is identical, the formula gives zero, but no maximum is attained over strictly positive Gaussian variances: the likelihood grows without bound as the variance approaches zero. The positive floor used below keeps the fitted density away from that zero-variance boundary. The relative difference between the two variance estimates decreases as grows. This is the same normal maximum likelihood calculation we saw in Maximum Likelihood Estimation.
The implementation uses the log density:
where:
- : the log density of feature given class
- : the mean of feature within class
- : the variance of feature within class
- : the observed value of feature
Let us derive this slowly. Start with the density:
Take the logarithm of the whole expression. The logarithm of a product is the sum of logarithms:
The first term is . The second term is just the exponent because . So we obtain the expression above. The constant term depends on the class through , so it is not the same for every class and must be included.
In practice, a class may have zero variance for a feature if all its training values are identical. Then the log density contains and the squared-distance term divides by zero. We fix this by adding a small positive constant to every variance:
Here is a small number such as , and is the variance of feature over the entire training set. The maximum is taken across features. This is the convention used by scikit-learn's GaussianNB through its var_smoothing parameter. With and at least one feature having positive global training variance, this gives a positive smoothing constant. If every global variance is zero, the formula also gives zero; our implementation rejects any remaining nonpositive class variance instead of claiming smoothing repaired it.
For multinomial naive Bayes, the data are nonnegative integer counts rather than continuous measurements. Conditional on the class and document length, tokens are independent categorical draws. The resulting count components are multinomial and are generally dependent when the length is fixed. The classifier below conditions on length, omitting a separate class-dependent length model. Each observation is a count vector , where is the number of times word occurs in a document, and is the vocabulary size. The document length is . The multinomial probability of the document given class is
where:
- : the document's count vector, with the number of times word occurs
- : the document length,
- : the factorial of the count of word , used in the multinomial coefficient
- : the probability of any particular ordering of the word tokens with those counts
- : the probability that a randomly chosen token from a document of class is word
- : the vocabulary size
The fraction is the multinomial coefficient. It counts the number of distinct orderings of the word tokens when there are tokens of each word. The product gives the probability of each token under the class-specific word distribution. The parameter is the probability that a randomly chosen token from a document of class is word , constrained so that the class-specific word probabilities sum to one.
The multinomial coefficient depends only on the document, not on the class. When we compare classes, it appears in every numerator and in the denominator, so it cancels. Therefore, for classification the likelihood is proportional to the product of class-specific word probabilities, with the proportionality factor independent of the class. This gives
Taking logs gives
where:
- : the log multinomial coefficient , which depends only on the document and is the same for every class
- : the vocabulary size
- : the count of word in the document
- : the probability that a randomly chosen token from a document of class is word
The constant is the same for all classes and does not affect the decision or the normalized posterior. The implementation below therefore stores log word probabilities and omits the class-independent multinomial coefficient from its class scores.
The maximum likelihood estimate of is the fraction of word tokens in class that are word :
where:
- : the total count of word in class
- : the total number of word tokens in class
The unsmoothed estimate requires a positive class token total . With smoothing parameter , even a class with zero observed tokens receives a defined uniform word distribution. We add pseudo-counts:
The numerator adds to every word count. The denominator adds so that the probabilities still sum to one. When , this is Laplace smoothing. When , it is sometimes called Lidstone smoothing. When , we recover the unsmoothed maximum likelihood estimate, which can be zero and cause the zero-frequency problem.
A related model is the Bernoulli event model. It represents a document by binary presence indicators rather than counts. The likelihood, over the fixed vocabulary of size , is
Here is the probability that word appears at least once in a document of class . The Bernoulli model explicitly penalizes words that are absent, because each absent word contributes the factor , while the multinomial model only looks at words that are present: a zero count contributes the factor and therefore no evidence. The smoothed estimate is
where is the number of documents in class that contain word , and is the number of documents in class . The denominator has because each word contributes two possible outcomes: present or absent.
Smoothing and stable log-probability computation
Two of the formulas above can fail on real data, and both failures are worth understanding rather than patching over. Smoothing solves the statistical failure; log-sum-exp solves the numerical one. They are separate problems that happen to appear in the same chapter.
Smoothing addresses a statistical issue: with limited data, a word or feature value may be missing from a class sample by chance. The unsmoothed estimate sets its probability to zero, which is an extreme claim: it asserts that the event is impossible, based on the absence of evidence rather than on evidence of absence. It also creates a numerical problem, because is negative infinity and a single such term wipes out every other piece of evidence in the score. Adding pseudo-counts keeps every probability strictly positive and regularizes the estimate toward a uniform distribution.
For multinomial naive Bayes, the effect of is easy to see. A larger pulls every toward . A smaller lets the observed counts dominate. If we set too small, rare words still get very small probabilities and the model can be unstable. As tends to infinity with the observed counts fixed, every class word distribution tends to uniform and predictions tend toward the prior. In practice, is a reasonable default, and we can tune it with cross-validation. The same principle applies to the Gaussian variance smoothing parameter : it should be small enough not to distort real variance differences, but large enough to prevent division by zero.
Even with strictly positive probabilities, multiplying many numbers can underflow. Suppose a document has 500 words and each word has probability . The product is , which is far below the smallest representable positive double. The base-10 logarithm of the product is , so the natural logarithm is , which is a perfectly manageable floating-point number. This is why we compute scores in log space.
After computing the log scores , we need to normalize them into probabilities. A direct computation of can overflow if some scores are large, or underflow if all scores are very negative. For finite class scores, log-sum-exp avoids exponentiating their common large scale. Let
Then
The subtraction makes the largest exponent zero, so the largest term in the sum is . The sum is therefore between and , which is numerically safe. The normalized posterior is
For finite scores this is mathematically identical to the original formula. Individual extremely small posterior probabilities may still round to zero, while their log probabilities remain available. The reordering protects the normalization without changing the model. In code, scipy.special.logsumexp implements this calculation.
For Gaussian naive Bayes, the same log-sum-exp step is used after we compute the joint log-likelihood for each class. Positive variances make the Gaussian log-density formula well defined. Extreme finite measurements can still overflow squared residuals; these teaching classes reject nonfinite computed scores. Variance smoothing and score normalization address different numerical problems.
Mathematical properties
With the formulas in place, it is worth asking what kind of model we have built and where its behaviour comes from. Three properties matter for practice: the model is generative, its decision boundary has a specific geometric shape, and its parameter count is linear in the dimension.
Naive Bayes is a generative classifier. It specifies a full probability model for the features and the label, then uses Bayes' theorem to classify. This is different from a discriminative classifier such as logistic regression, which models the conditional probability of the label directly. Generative models can be trained with unlabeled data in some settings, can handle missing features by marginalizing over them, and can generate synthetic observations. Discriminative models learn the label conditional or decision rule directly and can be more accurate when the generative assumptions are wrong; the comparison still depends on the model family and available training data.
For Gaussian naive Bayes, the decision boundary has a specific shape. The difference between the log scores of two classes and is
The squared terms make this a quadratic function of when the class variances differ. The boundary is therefore a quadratic surface. If the variances are shared across classes, so that for every feature , the quadratic terms cancel and the boundary becomes linear. This connects naive Bayes to linear and quadratic discriminant analysis. With a shared diagonal covariance matrix, Gaussian naive Bayes is a diagonal LDA. With class-specific diagonal covariance matrices, it is a diagonal QDA. We will study the full-covariance versions in the next chapter.
The parameter count is another important property. Gaussian naive Bayes has priors, means, and variances, for parameters. Multinomial naive Bayes has priors and word probabilities, for parameters. A full multivariate Gaussian with class-specific covariance matrices would have parameters. The linear parameter count is what makes naive Bayes usable in high dimensions.
These counts include all stored prior probabilities, although their sum-to-one constraint leaves only free prior parameters. Multinomial word probabilities likewise have free parameters per class. The full-covariance count below includes only the distinct entries of each symmetric covariance matrix.
The asymptotic notation becomes clearer when plotted. The next figure compares linear and quadratic parameter growth over a range of feature dimensions.
PythonIn [3]Expand
import numpy as np
K_params = 3
d_params = np.arange(1, 81)
nb_params = K_params + 2 * K_params * d_params
full_cov_params = (
K_params + K_params * d_params + K_params * d_params * (d_params + 1) / 2
)VisualizationOut [4]Expand

For fixed feature dimension and positive class probabilities, correctly specified Gaussian or multinomial class models admit consistent parameter estimates under the usual sampling and nondegeneracy conditions. Regularization must become negligible: Gaussian variance additions should tend to zero, while multinomial pseudo-counts can remain fixed because their ratio to growing class token totals then vanishes. With these conditions, the induced rule approaches Bayes risk. A misspecified independence model need not recover the true posterior, although its decision rule can still be useful.
Finally, good classification does not imply good probability estimates. Naive Bayes often ranks observations correctly even when its posterior probabilities are overconfident. If we need calibrated probabilities for risk assessment or decision making, we must check calibration separately. We will return to this point in the practical implications.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!