Naive Bayes
A fast probabilistic classifier based on Bayes' theorem and the assumption of independent features.
Bayes' theorem
$$P(y \mid \mathbf{x}) = \frac{P(\mathbf{x} \mid y)\,P(y)}{P(\mathbf{x})}$$
With the conditional independence assumption:
$$P(y \mid x_1, \dots, x_p) \propto P(y) \prod_{j=1}^{p} P(x_j \mid y)$$
We choose the class with the largest posterior probability. In practice we add logarithms instead of multiplying small probabilities, to avoid numerical precision problems.
Variants
| Type | Suitable data |
|---|---|
GaussianNB | Continuous numerical features |
MultinomialNB | Counts (word counts) |
BernoulliNB | Binary features (presence or absence of a word) |
ComplementNB | Texts with imbalanced classes |
Example: classifying short messages
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
texts = ["special offer win a prize now", "the meeting is tomorrow morning",
"win a free phone", "I sent you the lecture file"]
labels = ["spam", "ham", "spam", "ham"]
clf = make_pipeline(CountVectorizer(), MultinomialNB(alpha=1.0))
clf.fit(texts, labels)
print(clf.predict(["a free prize for you"]))alpha=1.0 is Laplace smoothing. The example is for illustration only; a real model needs thousands of examples and sound evaluation.
Advantages and limitations
- Very fast, and works with relatively little training data.
- A good baseline for text classification.
- Its probability estimates are often poorly calibrated (overconfident), so do not rely on them as accurate probabilities without calibration.
Lesson terms
- Conditional independence
- The assumption that the features do not influence one another once the class is known.
- Laplace smoothing
- Adding a small number to every count to avoid zero probabilities for words or values that did not appear in training.
- Bayes' theorem
- A relationship linking the posterior probability to the prior probability and the likelihood: P(y|x) = P(x|y)P(y)/P(x).
Abstract
The naive Bayes classifier applies Bayes' theorem to compute the probability of a class given the features, with the simplifying assumption that the features are conditionally independent given the class. Although the assumption rarely holds, the classifier works well on problems such as text classification, and it is very fast at training and prediction. Its variants include Gaussian, Multinomial and Bernoulli.
Review questions
-
What is the “naive” assumption in this classifier?
That the features are conditionally independent given the class.
-
Which type of naive Bayes suits word counts in texts?
MultinomialNB.
Sources and references
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate