Naive Bayes classifier explained

In statistics, naive Bayes classifiers are a family of linear "probabilistic classifiers" which assumes that the features are conditionally independent, given the target class. The strength (naivety) of this assumption is what gives the classifier its name. These classifiers are among the simplest Bayesian network models.[1]

Naive Bayes classifiers are highly scalable, requiring a number of parameters linear in the number of variables (features/predictors) in a learning problem. Maximum-likelihood training can be done by evaluating a closed-form expression, which takes linear time, rather than by expensive iterative approximation as used for many other types of classifiers.

In the statistics literature, naive Bayes models are known under a variety of names, including simple Bayes and independence Bayes.[2] All these names reference the use of Bayes' theorem in the classifier's decision rule, but naive Bayes is not (necessarily) a Bayesian method.[3]

Introduction

Naive Bayes is a simple technique for constructing classifiers: models that assign class labels to problem instances, represented as vectors of feature values, where the class labels are drawn from some finite set. There is not a single algorithm for training such classifiers, but a family of algorithms based on a common principle: all naive Bayes classifiers assume that the value of a particular feature is independent of the value of any other feature, given the class variable. For example, a fruit may be considered to be an apple if it is red, round, and about 10 cm in diameter. A naive Bayes classifier considers each of these features to contribute independently to the probability that this fruit is an apple, regardless of any possible correlations between the color, roundness, and diameter features.

In many practical applications, parameter estimation for naive Bayes models uses the method of maximum likelihood; in other words, one can work with the naive Bayes model without accepting Bayesian probability or using any Bayesian methods.

Despite their naive design and apparently oversimplified assumptions, naive Bayes classifiers have worked quite well in many complex real-world situations. In 2004, an analysis of the Bayesian classification problem showed that there are sound theoretical reasons for the apparently implausible efficacy of naive Bayes classifiers.[4] Still, a comprehensive comparison with other classification algorithms in 2006 showed that Bayes classification is outperformed by other approaches, such as boosted trees or random forests.[5]

An advantage of naive Bayes is that it only requires a small amount of training data to estimate the parameters necessary for classification.[6]

Probabilistic model

Abstractly, naive Bayes is a conditional probability model: it assigns probabilities

p(Ck\midx1,\ldots,xn)

for each of the possible outcomes or classes

Ck

given a problem instance to be classified, represented by a vector

x=(x1,\ldots,xn)

encoding some features (independent variables).[7]

The problem with the above formulation is that if the number of features is large or if a feature can take on a large number of values, then basing such a model on probability tables is infeasible. The model must therefore be reformulated to make it more tractable. Using Bayes' theorem, the conditional probability can be decomposed as:p(C_k \mid \mathbf) = \frac \,

In plain English, using Bayesian probability terminology, the above equation can be written as\text = \frac \,

In practice, there is interest only in the numerator of that fraction, because the denominator does not depend on

C

and the values of the features

xi

are given, so that the denominator is effectively constant.The numerator is equivalent to the joint probability modelp(C_k, x_1, \ldots, x_n)\,which can be rewritten as follows, using the chain rule for repeated applications of the definition of conditional probability:\beginp(C_k, x_1, \ldots, x_n) & = p(x_1, \ldots, x_n, C_k) \\ & = p(x_1 \mid x_2, \ldots, x_n, C_k) \ p(x_2, \ldots, x_n, C_k) \\ & = p(x_1 \mid x_2, \ldots, x_n, C_k) \ p(x_2 \mid x_3, \ldots, x_n, C_k) \ p(x_3, \ldots, x_n, C_k) \\ & = \cdots \\ & = p(x_1 \mid x_2, \ldots, x_n, C_k) \ p(x_2 \mid x_3, \ldots, x_n, C_k) \cdots p(x_ \mid x_n, C_k) \ p(x_n \mid C_k) \ p(C_k) \\\end

Now the "naive" conditional independence assumptions come into play: assume that all features in

x

are mutually independent, conditional on the category

Ck

. Under this assumption,p(x_i \mid x_, \ldots,x_, C_k) = p(x_i \mid C_k)\,.

Thus, the joint model can be expressed as\beginp(C_k \mid x_1, \ldots, x_n) \varpropto\ & p(C_k, x_1, \ldots, x_n) \\ & = p(C_k) \ p(x_1 \mid C_k) \ p(x_2\mid C_k) \ p(x_3\mid C_k) \ \cdots \\ & = p(C_k) \prod_^n p(x_i \mid C_k)\,,\endwhere

\varpropto

denotes proportionality since the denominator

p(x)

is omitted.

This means that under the above independence assumptions, the conditional distribution over the class variable

C

is:p(C_k \mid x_1, \ldots, x_n) = \frac \ p(C_k) \prod_^n p(x_i \mid C_k)where the evidence

Z=p(x)=\sumkp(Ck)p(x\midCk)

is a scaling factor dependent only on

x1,\ldots,xn

, that is, a constant if the values of the feature variables are known.

Constructing a classifier from the probability model

The discussion so far has derived the independent feature model, that is, the naive Bayes probability model. The naive Bayes classifier combines this model with a decision rule. One common rule is to pick the hypothesis that is most probable so as to minimize the probability of misclassification; this is known as the maximum a posteriori or MAP decision rule. The corresponding classifier, a Bayes classifier, is the function that assigns a class label

\hat{y}=Ck

for some as follows:\hat = \underset \ p(C_k) \displaystyle\prod_^n p(x_i \mid C_k).

Parameter estimation and event models

A class's prior may be calculated by assuming equiprobable classes, i.e.,

p(Ck)=

1
K
, or by calculating an estimate for the class probability from the training set:\text = \frac \,To estimate the parameters for a feature's distribution, one must assume a distribution or generate nonparametric models for the features from the training set.[8]

The assumptions on distributions of features are called the "event model" of the naive Bayes classifier. For discrete features like the ones encountered in document classification (include spam filtering), multinomial and Bernoulli distributions are popular. These assumptions lead to two distinct models, which are often confused.[9] [10]

Gaussian naive Bayes

When dealing with continuous data, a typical assumption is that the continuous values associated with each class are distributed according to a normal (or Gaussian) distribution. For example, suppose the training data contains a continuous attribute,

x

. The data is first segmented by the class, and then the mean and variance of

x

is computed in each class. Let

\muk

be the mean of the values in

x

associated with class

Ck

, and let
2
\sigma
k
be the Bessel corrected variance of the values in

x

associated with class

Ck

. Suppose one has collected some observation value

v

. Then, the probability density of

v

given a class

Ck

, i.e.,

p(x=v\midCk)

, can be computed by plugging

v

into the equation for a normal distribution parameterized by

\muk

and
2
\sigma
k
. Formally,p(x=v \mid C_k) = \frac\,e^

Another common technique for handling continuous values is to use binning to discretize the feature values and obtain a new set of Bernoulli-distributed features. Some literature suggests that this is required in order to use naive Bayes, but it is not true, as the discretization may throw away discriminative information.[2]

Sometimes the distribution of class-conditional marginal densities is far from normal. In these cases, kernel density estimation can be used for a more realistic estimate of the marginal densities of each class. This method, which was introduced by John and Langley,[8] can boost the accuracy of the classifier considerably.[11] [12]

Multinomial naive Bayes

(p1,...,pn)

where

pi

is the probability that event occurs (or such multinomials in the multiclass case). A feature vector

x=(x1,...,xn)

is then a histogram, with

xi

counting the number of times event was observed in a particular instance. This is the event model typically used for document classification, with events representing the occurrence of a word in a single document (see bag of words assumption). The likelihood of observing a histogram is given by:p(\mathbf \mid C_k) = \frac \prod_^n ^where

pki:=p(xi\midCk)

.

The multinomial naive Bayes classifier becomes a linear classifier when expressed in log-space:[13] \begin\log p(C_k \mid \mathbf) & \varpropto \log \left(p(C_k) \prod_^n ^ \right) \\ & = \log p(C_k) + \sum_^n x_i \cdot \log p_ \\ & = b + \mathbf_k^\top \mathbf\endwhere

b=logp(Ck)

and

wki=logpki

. Estimating the parameters in log space is advantageous since multiplying a large number of small values can lead to significant rounding error. Applying a log transform reduces the effect of this rounding error.

If a given class and feature value never occur together in the training data, then the frequency-based probability estimate will be zero, because the probability estimate is directly proportional to the number of occurrences of a feature's value. This is problematic because it will wipe out all information in the other probabilities when they are multiplied. Therefore, it is often desirable to incorporate a small-sample correction, called pseudocount, in all probability estimates such that no probability is ever set to be exactly zero. This way of regularizing naive Bayes is called Laplace smoothing when the pseudocount is one, and Lidstone smoothing in the general case.

Rennie et al. discuss problems with the multinomial assumption in the context of document classification and possible ways to alleviate those problems, including the use of tf–idf weights instead of raw term frequencies and document length normalization, to produce a naive Bayes classifier that is competitive with support vector machines.[13]

Bernoulli naive Bayes

In the multivariate Bernoulli event model, features are independent Boolean variables (binary variables) describing inputs. Like the multinomial model, this model is popular for document classification tasks,[9] where binary term occurrence features are used rather than term frequencies. If

xi

is a Boolean expressing the occurrence or absence of the 'th term from the vocabulary, then the likelihood of a document given a class

Ck

is given by:[9] p(\mathbf \mid C_k) = \prod_^n p_^ (1 - p_)^where

pki

is the probability of class

Ck

generating the term

xi

. This event model is especially popular for classifying short texts. It has the benefit of explicitly modelling the absence of terms. Note that a naive Bayes classifier with a Bernoulli event model is not the same as a multinomial NB classifier with frequency counts truncated to one.

Semi-supervised parameter estimation

Given a way to train a naive Bayes classifier from labeled data, it's possible to construct a semi-supervised training algorithm that can learn from a combination of labeled and unlabeled data by running the supervised learning algorithm in a loop:

  1. Given a collection

D=L\uplusU

of labeled samples and unlabeled samples, start by training a naive Bayes classifier on .
  1. Until convergence, do:
    1. Predict class probabilities

P(C\midx)

for all examples in

D

.
    1. Re-train the model based on the probabilities (not the labels) predicted in the previous step.

Convergence is determined based on improvement to the model likelihood

P(D\mid\theta)

, where

\theta

denotes the parameters of the naive Bayes model.

This training algorithm is an instance of the more general expectation–maximization algorithm (EM): the prediction step inside the loop is the E-step of EM, while the re-training of naive Bayes is the M-step. The algorithm is formally justified by the assumption that the data are generated by a mixture model, and the components of this mixture model are exactly the classes of the classification problem.[14]

Discussion

Despite the fact that the far-reaching independence assumptions are often inaccurate, the naive Bayes classifier has several properties that make it surprisingly useful in practice. In particular, the decoupling of the class conditional feature distributions means that each distribution can be independently estimated as a one-dimensional distribution. This helps alleviate problems stemming from the curse of dimensionality, such as the need for data sets that scale exponentially with the number of features. While naive Bayes often fails to produce a good estimate for the correct class probabilities,[15] this may not be a requirement for many applications. For example, the naive Bayes classifier will make the correct MAP decision rule classification so long as the correct class is predicted as more probable than any other class. This is true regardless of whether the probability estimate is slightly, or even grossly inaccurate. In this manner, the overall classifier can be robust enough to ignore serious deficiencies in its underlying naive probability model.[16] Other reasons for the observed success of the naive Bayes classifier are discussed in the literature cited below.

Relation to logistic regression

In the case of discrete inputs (indicator or frequency features for discrete events), naive Bayes classifiers form a generative-discriminative pair with multinomial logistic regression classifiers: each naive Bayes classifier can be considered a way of fitting a probability model that optimizes the joint likelihood

p(C,x)

, while logistic regression fits the same probability model to optimize the conditional

p(C\midx)

.[17]

More formally, we have the following:

The link between the two can be seen by observing that the decision function for naive Bayes (in the binary case) can be rewritten as "predict class

C1

if the odds of

p(C1\midx)

exceed those of

p(C2\midx)

". Expressing this in log-space gives:\log\frac = \log p(C_1 \mid \mathbf) - \log p(C_2 \mid \mathbf) > 0

The left-hand side of this equation is the log-odds, or logit, the quantity predicted by the linear model that underlies logistic regression. Since naive Bayes is also a linear model for the two "discrete" event models, it can be reparametrised as a linear function

b+w\topx>0

. Obtaining the probabilities is then a matter of applying the logistic function to

b+w\topx

, or in the multiclass case, the softmax function.

Discriminative classifiers have lower asymptotic error than generative ones; however, research by Ng and Jordan has shown that in some practical cases naive Bayes can outperform logistic regression because it reaches its asymptotic error faster.[17]

Examples

Person classification

Problem: classify whether a given person is a male or a female based on the measured features.The features include height, weight, and foot size. Although with NB classifier we treat them as independent, they are not in reality.

Training

Example training set below.

Person height (feet) weight (lbs) foot size (inches)
male 6 180 12
male 5.92 (5'11") 190 11
male 5.58 (5'7") 170 12
male 5.92 (5'11") 165 10
female 5 100 6
female 5.5 (5'6") 150 8
female 5.42 (5'5") 130 7
female 5.75 (5'9") 150 9

The classifier created from the training set using a Gaussian distribution assumption would be (given variances are unbiased sample variances):

Person mean (height) variance (height) mean (weight) variance (weight) mean (foot size) variance (foot size)
male 5.855 3.5033 × 10−2 176.25 1.2292 × 102 11.25 9.1667 × 10−1
female 5.4175 9.7225 × 10−2 132.5 5.5833 × 102 7.5 1.6667

The following example assumes equiprobable classes so that P(male)= P(female) = 0.5. This prior probability distribution might be based on prior knowledge of frequencies in the larger population or in the training set.

Testing

Below is a sample to be classified as male or female.

In order to classify the sample, one has to determine which posterior is greater, male or female. For the classification as male the posterior is given by\text = \frac

For the classification as female the posterior is given by\text = \frac

The evidence (also termed normalizing constant) may be calculated:\begin\text = P(\text) \, p(\text \mid \text) \, p(\text \mid \text) \, p(\text \mid \text) \\+ P(\text) \, p(\text \mid \text) \, p(\text \mid \text) \, p(\text \mid \text)\end

However, given the sample, the evidence is a constant and thus scales both posteriors equally. It therefore does not affect classification and can be ignored. The probability distribution for the sex of the sample can now be determined:P(\text) = 0.5p(\mid \text) = \frac\exp\left(\frac\right) \approx 1.5789,where

\mu=5.855

and

\sigma2=3.503310-2

are the parameters of normal distribution which have been previously determined from the training set. Note that a value greater than 1 is OK here – it is a probability density rather than a probability, because height is a continuous variable.

p(\mid \text) = \frac\exp\left(\frac\right) = 5.9881 \cdot 10^p(\mid \text) = \frac\exp\left(\frac\right) = 1.3112 \cdot 10^\text = \text = 6.1984 \cdot 10^

P = 0.5p(\mid) = 2.23 \cdot 10^p(\mid) = 1.6789 \cdot 10^p(\mid) = 2.8669 \cdot 10^\text = \text = 5.3778 \cdot 10^

Since posterior numerator is greater in the female case, the prediction is that the sample is female.

Document classification

Here is a worked example of naive Bayesian classification to the document classification problem.Consider the problem of classifying documents by their content, for example into spam and non-spam e-mails. Imagine that documents are drawn from a number of classes of documents which can be modeled as sets of words where the (independent) probability that the i-th word of a given document occurs in a document from class C can be written asp(w_i \mid C)\,

(For this treatment, things are further simplified by assuming that words are randomly distributed in the document - that is, words are not dependent on the length of the document, position within the document with relation to other words, or other document-context.)

Then the probability that a given document D contains all of the words

wi

, given a class C, isp(D\mid C) = \prod_i p(w_i \mid C)\,

The question that has to be answered is: "what is the probability that a given document D belongs to a given class C?" In other words, what is

p(C\midD)

?

Now by definitionp(D\mid C)=andp(C \mid D) =

Bayes' theorem manipulates these into a statement of probability in terms of likelihood.p(C\mid D) = \frac

Assume for the moment that there are only two mutually exclusive classes, S and ¬S (e.g. spam and not spam), such that every element (email) is in either one or the other;p(D\mid S)=\prod_i p(w_i \mid S)\,andp(D\mid\neg S)=\prod_i p(w_i\mid\neg S)\,

Using the Bayesian result above, one can write:p(S\mid D)=\,\prod_i p(w_i \mid S)p(\neg S\mid D)=\,\prod_i p(w_i \mid\neg S)

Dividing one by the other gives:=

Which can be re-factored as:=\,\prod_i

Thus, the probability ratio p(S | D) / p(¬S | D) can be expressed in terms of a series of likelihood ratios.The actual probability p(S | D) can be easily computed from log (p(S | D) / p(¬S | D)) based on the observation that p(S | D) + p(¬S | D) = 1.

Taking the logarithm of all these ratios, one obtains:\ln=\ln+\sum_i \ln

(This technique of "log-likelihood ratios" is a common technique in statistics.In the case of two mutually exclusive alternatives (such as this example), the conversion of a log-likelihood ratio to a probability takes the form of a sigmoid curve: see logit for details.)

Finally, the document can be classified as follows. It is spam if

p(S\midD)>p(\negS\midD)

(i. e.,

ln{p(S\midD)\overp(\negS\midD)}>0

), otherwise it is not spam.

See also

Further reading

External links

Notes and References

  1. Web site: McCallum . Andrew . Graphical Models, Lecture2: Bayesian Network Representation . https://ghostarchive.org/archive/20221009/https://people.cs.umass.edu/~mccallum/courses/gm2011/02-bn-rep.pdf . 2022-10-09 . live . 22 October 2019.
  2. Hand . D. J. . Yu . K. . 2001 . Idiot's Bayes — not so stupid after all? . International Statistical Review . 69 . 3 . 385–399 . 0306-7734 . 10.2307/1403452. 1403452 .
  3. 2.
  4. Harry . Zhang . The Optimality of Naive Bayes . FLAIRS2004 conference .
  5. Caruana . R. . Niculescu-Mizil . A. . An empirical comparison of supervised learning algorithms . Proc. 23rd International Conference on Machine Learning . 2006 . 10.1.1.122.5901 .
  6. Web site: Why does Naive Bayes work better when the number of features >> sample size compared to more sophisticated ML algorithms? . Cross Validated Stack Exchange . 24 January 2023.
  7. Book: Narasimha Murty . M. . Susheela Devi . V. . Pattern Recognition: An Algorithmic Approach . 2011 . 978-0857294944 .
  8. George H. . John . Pat . Langley . 1995 . Estimating Continuous Distributions in Bayesian Classifiers . Proc. Eleventh Conf. on Uncertainty in Artificial Intelligence . 338–345 . Morgan Kaufmann . 1302.4964 .
  9. McCallum . Andrew . Kamal . Nigam . A comparison of event models for Naive Bayes text classification . AAAI-98 workshop on learning for text categorization . 752 . 1998 . https://ghostarchive.org/archive/20221009/http://www.kamalnigam.com/papers/multinomial-aaaiws98.pdf . 2022-10-09 . live.
  10. Metsis . Vangelis . Ion . Androutsopoulos . Georgios . Paliouras . Spam filtering with Naive Bayes—which Naive Bayes? . Third conference on email and anti-spam (CEAS) . 17 . 2006.
  11. Piryonesi . S. Madeh . El-Diraby . Tamer E. . 2020-06-01 . Role of Data Analytics in Infrastructure Asset Management: Overcoming Data Size and Quality Problems . Journal of Transportation Engineering, Part B: Pavements . 146 . 2 . 04020022 . 10.1061/JPEODX.0000175 . 216485629.
  12. Book: Hastie, Trevor. . The elements of statistical learning : data mining, inference, and prediction : with 200 full-color illustrations . 2001 . Springer . Tibshirani, Robert., Friedman, J. H. (Jerome H.) . 0-387-95284-5 . New York . 46809224.
  13. Rennie . J. . Shih . L. . Teevan . J. . Karger . D. . Tackling the poor assumptions of naive Bayes classifiers . ICML . 2003 . https://ghostarchive.org/archive/20221009/http://people.csail.mit.edu/~jrennie/papers/icml03-nb.pdf . 2022-10-09 . live.
  14. Kamal . Nigam . Andrew . McCallum . Sebastian . Thrun . Tom . Mitchell . Learning to classify text from labeled and unlabeled documents using EM . . 39 . 2/3 . 103–134 . 2000 . https://ghostarchive.org/archive/20221009/http://www.kamalnigam.com/papers/emcat-aaai98.pdf . 2022-10-09 . live. 10.1023/A:1007692713085 . 686980 . free .
  15. Niculescu-Mizil . Alexandru . Rich . Caruana . Predicting good probabilities with supervised learning . ICML . 2005 . 10.1145/1102351.1102430 . 2016-04-24 . https://web.archive.org/web/20140311005243/http://machinelearning.wustl.edu/mlpapers/paper_files/icml2005_Niculescu-MizilC05.pdf . 2014-03-11 . dead .
  16. Rish. Irina. 2001. An empirical study of the naive Bayes classifier. https://ghostarchive.org/archive/20221009/http://www.research.ibm.com/people/r/rish/papers/RC22230.pdf . 2022-10-09 . live. IJCAI Workshop on Empirical Methods in AI.
  17. Andrew Y. . Ng . Andrew Ng . Michael I. . Jordan . Michael I. Jordan . On discriminative vs. generative classifiers: A comparison of logistic regression and naive Bayes . . 14 . 2002 .