# Avoiding underflows in Gaussian Naive Bayes

There are mainly two ways to avoid numerical instability when implementing Gaussian Naive Bayes (GNB). Either one applies the log-sum-exp trick or one takes the logarithm and increases the variance by some number $\varepsilon$. In this blog post, I will follow the second approach.

## Derivation 1

Let us first derive GNB via Bayes’ theorem.

$f_{X_1, \dots, X_n}(\mathbf{x})$ can be removed because the term does not depend on $Y$.

Assume the features $X_1, \dots, X_n$ are conditional independent given $Y$. Then

Next, either use the likelihood ratio test or MAP as decision rule. We will use MAP and obtain

Assume $X_i \mid Y=j \sim \mathcal{N}(\mu_{ji}, \sigma_{ji})$.

The result is GNB. In order to avoid underflows, we apply the logarithm.

After removing some constants, we get

You could use the formula as it is now. However, I will go one step further and assume the uniform prior $f_{Y=j}(j) = \frac{1}{m}$. We can simplify the equation even more.

## Derivation 2

Before implementing GNB, I will provide an alternative derivation via Quadratic Discriminant Analysis (QDA).

QDA assumes like GNB normal distributed features, but it does not assume conditional independence.

Let us derive GNB from QDA, which is given by the following equation:

Remove constants, prior and use arg min.

Assume conditional independence. Recall that when two random variables are independent, their covariance is zero.

Hence, this assumption will turn $\boldsymbol{\Sigma}_j$ into a diagonal matrix. The determinant becomes $\log\left(\prod_{i=1}^n\boldsymbol{\Sigma}_{j,ii}\right) = \sum_{i=1}^n \log\left(\boldsymbol{\Sigma}_{j,ii}\right)$. By replacing also the second term, we obtain GNB.

## Implementation

The following code is a direct implementation of equation (1).

There is one difference with respect to (1). We have to increase the variance by some small number $\epsilon$ to avoid numerical errors. These happen due to our fraction $\frac{1}{\sigma^2_{ji}}$. If you read the scikit-learn code, you will find out that they also use this trick.

This code gives the same accuracy as scikit-learn’s implementation of GNB. However, I didn’t test this extensively.

Categories:

Updated: