AI voor Iedereen

Search

Search chapters and demos

๐Ÿ‘ถ Naive Bayes

๐Ÿท๏ธ Classification

Many AI systems essentially do one thing: they stick a label on something. Is this email spam or genuine? Is there a dog or a cat in this photo? Is this bank transaction suspicious or not? The system receives an input and has to decide which category it belongs to. We call that classification.

Classification Definition

Classification is assigning a data point (a photo, a text, a list of properties) to one of a set of predefined labels (also called "categories" or "classes"), based on the features of that data point.

Try it yourself: drag the green rectangle below and make it larger or smaller, so that as many points as possible are classified correctly. Points with a + are positive, points with a โˆ’ are negative, and everything inside the rectangle is predicted positive.

Loading demo

The percentage of correctly classified points that the demo shows is called the accuracy: the simplest measure of how well a classification model works.

So what does such a system look at? At the features of the input. In the demo above, those are simply two numbers, one on the x-axis and one on the y-axis. But there can also be many more, and more complex, features: for an animal, the shape of its ears, its snout and its fur; for an email, the sender, the words and the attachments.

Feature Definition

A feature is a measurable property of a data point that serves as input for a learning algorithm. A feature can be, for example, a number (age, height), a category (color, origin) or a yes/no value (does the email contain the word "free"?).

There are many different ways to determine such a label with machine learning. In this chapter, we do it with probability calculations, based on how often features occur in other data points. For every possible label, we calculate how likely it is, and we choose the label with the highest probability. You already know the tools for this from the chapter on probability: counting, multiplying and Bayes' theorem.

๐Ÿ‘ถ Naive Bayes

๐Ÿฝ๏ธ A picky eater

You are going out to eat with a friend who is a very picky eater, and you want to estimate in advance whether he will like a dish. Luckily, for ten earlier dishes you kept track of the origin, the dominant flavor and the texture, and of whether he liked it:

๐Ÿฝ๏ธ Picky eater
How likely is the picky eater to enjoy the dish, given the origin of the meal, the dominant flavor and the texture of the food?
๐Ÿณ๏ธ๏ธ Origin
๐Ÿ‘… Flavor
๐Ÿฝ๏ธ Texture
๐Ÿ˜‹ Tasty
๐Ÿ Italian๐Ÿง‚ savory๐Ÿฅฃ soft๐Ÿ˜ Yes
๐Ÿœ Asian๐Ÿง‚ savory๐Ÿฅฃ soft๐Ÿ˜ Yes
๐Ÿœ Asian๐Ÿฏ sweet๐Ÿฅฃ soft๐Ÿ˜ Yes
๐ŸŒฎ Mexican๐Ÿฏ sweet๐Ÿฅ– crunchy๐Ÿ˜ Yes
๐Ÿ Italian๐Ÿฏ sweet๐Ÿฅ– crunchy๐Ÿ™… No
๐Ÿ Italian๐ŸŒถ๏ธ spicy๐Ÿฅ– crunchy๐Ÿ™… No
๐Ÿ Italian๐Ÿง‚ savory๐Ÿฅ– crunchy๐Ÿ™… No
๐Ÿœ Asian๐ŸŒถ๏ธ spicy๐Ÿฅฃ soft๐Ÿ™… No
๐ŸŒฎ Mexican๐ŸŒถ๏ธ spicy๐Ÿฅ– crunchy๐Ÿ™… No
๐ŸŒฎ Mexican๐Ÿง‚ savory๐Ÿฅฃ soft๐Ÿ™… No

This is labeled training data: examples for which you already know the right answer. Learning from such examples is called supervised learning.

Tonight, a new dish is on the menu: {๐Ÿœ Asian, ๐Ÿง‚ savory, ๐Ÿฅ– crunchy}. Will he like it? That exact combination is not in the table, so simply looking it up does not work. Naive Bayes solves this by not looking at the combination, but at each feature separately.

๐Ÿงฎ Counting and multiplying

The algorithm works in three steps, and in each step you simply count in the table. Tip: click the "๐Ÿ˜‹ Tasty" column to sort the table, which makes counting easier.

  1. ๐Ÿฅง The prior probability of each label. How often does he like something in general, before you even look at the dish? Of the 10 dishes, he liked 4:

    • P(๐Ÿ˜ Yes) = 410\frac{4}{10} = 40%
    • P(๐Ÿ™… No) = 610\frac{6}{10} = 60%

    This is the prior probability (or prior for short) from the chapter on probability: your starting expectation when you do not know anything about the dish yet.

  2. ๐Ÿ”Ž The probability of each feature, given the label. Now you look at each group separately. Of the 4 dishes he liked: how many were Asian, how many savory, how many crunchy? And the same for the 6 dishes he did not like.

    • ๐Ÿ˜ Yes (4 dishes):
      • P(๐Ÿœ Asian | ๐Ÿ˜ Yes) = 24\frac{2}{4} = 50%
      • P(๐Ÿง‚ savory | ๐Ÿ˜ Yes) = 24\frac{2}{4} = 50%
      • P(๐Ÿฅ– crunchy | ๐Ÿ˜ Yes) = 14\frac{1}{4} = 25%
    • ๐Ÿ™… No (6 dishes):
      • P(๐Ÿœ Asian | ๐Ÿ™… No) = 16\frac{1}{6} โ‰ˆ 16.7%
      • P(๐Ÿง‚ savory | ๐Ÿ™… No) = 26\frac{2}{6} โ‰ˆ 33.3%
      • P(๐Ÿฅ– crunchy | ๐Ÿ™… No) = 46\frac{4}{6} โ‰ˆ 66.7%

    Here we write P(๐Ÿœ Asian | ๐Ÿ˜ Yes) as shorthand for P(Origin = ๐Ÿœ Asian | Tasty = ๐Ÿ˜ Yes): the probability that a dish is Asian if you already know that he liked it. This is the likelihood of that feature.

  3. โœ–๏ธ Multiply into one score per label. For each label, you multiply the prior probability by the three probabilities from step 2:

    • Score(๐Ÿ˜ Yes) = 0.4 ยท 0.5 ยท 0.5 ยท 0.25 = 0.025
    • Score(๐Ÿ™… No) = 0.6 ยท 0.167 ยท 0.333 ยท 0.667 โ‰ˆ 0.022

    In plain words: start with how often the label occurs in general, and multiply by how well each feature fits that label.

Score(๐Ÿ˜ Yes) is the higher one, so you predict: he will like it. That is the whole algorithm: count, multiply per label and choose the highest score.

Probabilities are numbers between 0 and 1. Multiply a few of them and the result keeps getting smaller: 0.5 ยท 0.5 = 0.25 and 0.25 ยท 0.25 = 0.0625. The more features, the smaller the scores. That is not a problem: only their ratio matters. 0.025 versus 0.022 means the same as 25 versus 22.

Mathematically, the score looks like this for any dataset:

Naive Bayes score Rule

The score of a label is the prior probability of that label, multiplied by the probability of each feature of the data point given that label.

Score(label)=P(label)โ‹…P(feature1โˆฃlabel)โ‹…P(feature2โˆฃlabel)โ‹…โ€ฆโ‹…P(featurenโˆฃlabel)\text{Score}(\text{label}) = P(\text{label}) \cdot P(\text{feature}_1 \mid \text{label}) \cdot P(\text{feature}_2 \mid \text{label}) \cdot \ldots \cdot P(\text{feature}_n \mid \text{label})

Here P(label)P(\text{label}) is the prior probability (step 1), and each P(featureiโˆฃlabel)P(\text{feature}_i \mid \text{label}) is the probability of the ii-th feature of the new data point, given that label (step 2).

Would you rather have a percentage? The two scores do not add up to 100%, because they are not real probabilities yet (why not is explained in the in-depth section below). You can normalize them, though: divide each score by the sum of all scores. That way, P(๐Ÿ˜ย Yesโˆฃfeatures)โ‰ˆ0.0250.025+0.022โ‰ˆ53%P(\text{๐Ÿ˜ Yes} \mid \text{features}) \approx \frac{0.025}{0.025 + 0.022} \approx 53\%: just slightly more likely to be tasty than not. For the classification itself you do not need that step, because the highest score wins anyway.

Naive Bayes Definition

Naive Bayes is a classification algorithm that calculates a score for every possible label by multiplying the prior probability of that label by the probability of each feature of the data point, given that label. The label with the highest score is the prediction. It learns all those probabilities by counting in labeled training data.

Naive Bayes is not limited to yes or no. If a triage system has to choose between ๐ŸŸข OK, ๐ŸŸ  Follow up and ๐Ÿ”ด Refer, you calculate three scores: each label gets its own prior probability and its own probabilities per feature, and the label with the highest score wins.

๐ŸŽฒ Why "naive"?

Why are you allowed to simply multiply those probabilities in step 3? In the chapter on probability, you saw that multiplying is only correct when events are independent. Naive Bayes simply assumes that they are: once you know the label, the features no longer depend on each other.

Independence assumption of naive Bayes Definition

Naive Bayes assumes that the features are conditionally independent given the label: once you know the label, one feature tells you nothing more about another. That is why you can split the probability of the whole combination of features into a product of the separate probabilities per feature.

In the real world, that is rarely true. If the words "bank account" appear in an email, there is a good chance that "money" appears in it too, whether the email is spam or not. Naive Bayes ignores this and treats "bank account" and "money" as two separate pieces of evidence that happen to be in the same email. Hence the name: the assumption is naive.

So why make that assumption anyway? Without it, you would need to know, for every possible combination of features, how often it occurs in spam and in genuine email, with a joint probability distribution. That table grows exponentially. If, for 100 words, you only record whether or not each of them appears in an email, there are already 21002^{100} combinations: more than there are stars in the observable universe (external link). No collection of emails is large enough to have seen every combination even once, let alone to count a reliable probability for each. This is called the curse of dimensionality (external link): the more features, the sparser the data per combination. Increase the number of variables in the demo below and see how quickly the table becomes unmanageable.

Loading demo

The naive assumption cuts that one impossible problem into small, countable pieces. Instead of "how often does exactly this combination occur?", you only ask questions that you can answer with a handful of examples: how often is an email spam in general, how often does spam contain the word "free", how often does spam have more than five exclamation marks? That is how ten dishes were enough for the picky eater, even though there are eighteen possible combinations (3 origins ยท 3 flavors ยท 2 textures), eight of which you never saw. The new dish is one of them.

Even though the assumption is wrong, it works surprisingly well in practice: the scores are not perfect, but usually good enough to pick the right label. And because all it does is count, it is extremely fast.

๐Ÿ”„ Why does it work? The score derived from Bayes' theorem

Bayes' theorem tells you how to calculate P(BโˆฃA)P(B \mid A) from the reverse probability P(AโˆฃB)P(A \mid B):

P(BโˆฃA)=P(AโˆฃB)โ‹…P(B)P(A)P(B \mid A) = \frac{P(A \mid B) \cdot P(B)}{P(A)}

Fill in the label for BB and the list of features for AA (in bold because there are several):

P(labelโˆฃfeatures)=P(featuresโˆฃlabel)โ‹…P(label)P(features)P(\text{label} \mid \mathbf{features}) = \frac{P(\mathbf{features} \mid \text{label}) \cdot P(\text{label})}{P(\mathbf{features})}

The likelihood is exactly the probability of the whole combination, which we cannot count. This is where the independence assumption comes in: it splits that probability into a product of separate probabilities:

P(featuresโˆฃlabel)=P(feature1โˆฃlabel)โ‹…P(feature2โˆฃlabel)โ‹…โ€ฆโ‹…P(featurenโˆฃlabel)P(\mathbf{features} \mid \text{label}) = P(\text{feature}_1 \mid \text{label}) \cdot P(\text{feature}_2 \mid \text{label}) \cdot \ldots \cdot P(\text{feature}_n \mid \text{label})

Substituting this into Bayes' theorem gives:

P(labelโˆฃfeatures)=P(label)โ‹…P(feature1โˆฃlabel)โ‹…โ€ฆโ‹…P(featurenโˆฃlabel)P(features)P(\text{label} \mid \mathbf{features}) = \frac{P(\text{label}) \cdot P(\text{feature}_1 \mid \text{label}) \cdot \ldots \cdot P(\text{feature}_n \mid \text{label})}{P(\mathbf{features})}

The denominator P(features)P(\mathbf{features}) does not contain the label, so it is the same for every label. If you only want to know which label has the highest probability, you can leave it out. What remains is the numerator, and that is exactly the score from step 3:

Score(label)=P(label)โ‹…P(feature1โˆฃlabel)โ‹…โ€ฆโ‹…P(featurenโˆฃlabel)\text{Score}(\text{label}) = P(\text{label}) \cdot P(\text{feature}_1 \mid \text{label}) \cdot \ldots \cdot P(\text{feature}_n \mid \text{label})

This also explains why the scores do not add up to 100%: they are posterior probabilities from which you left out the common denominator. If you divide each score by the sum of all scores, you calculate that denominator after all, and you get the real posterior probabilities back.

Formally, you write the choice of the best label with the argโ€‰maxโก\argmax operator:

labelโˆ—=argโ€‰maxโกlabelScore(label)\text{label}^* = \argmax_{\text{label}} \text{Score}(\text{label})

The argโ€‰maxโก\argmax does not look for the highest score itself, but for which label produces that highest score. For the picky eater, Score(Yes) = 0.025 and Score(No) = 0.022, so labelโˆ—=Yes\text{label}^* = \text{Yes} (and not the number 0.025).

๐Ÿ•ธ๏ธ Naive Bayes as a Bayesian network

Naive Bayes is a special case of a Bayesian network, with a fixed structure: one node for the label, an arrow from that node to each feature, and no arrows between the features themselves. For the picky eater, it looks like this:

Arrows from Tasty to Origin, Flavor and Texture

Naive Bayes as a Bayesian network for the "Picky eater" example.

Those missing arrows between the features are precisely the independence assumption: given the label, the features do not depend on each other. The score from step 3 is nothing other than the chain rule of that network: the probability of the label, times the probability of each feature given its only parent, the label.

If you do want to model that features are related (for example, that "bank account" and "money" occur together), you draw extra arrows between the features. You then get a more general Bayesian network, at the cost of more probabilities to estimate from data.

๐Ÿฉน Smoothing

There is a catch: what if a feature value never occurred with a label in the training data?

Look at the picky eater again: not a single dish he liked was ๐ŸŒถ๏ธ spicy. So P(๐ŸŒถ๏ธ spicy | ๐Ÿ˜ Yes) = 04\frac{0}{4} = 0. If he is now served a spicy dish, Score(๐Ÿ˜ Yes) contains a factor 0, and the whole score becomes 0. Even if the dish suits his taste perfectly in every other respect, you predict "not tasty" with 100% certainty. Four examples are far too few to draw such a hard conclusion. In a spam filter with thousands of words, this happens all the time: one word that you never saw in a spam email, and the email can no longer be spam.

The solution is called Laplace smoothing (also called "add-one smoothing"): pretend that you saw every feature value with every label one extra time. In the counts of step 2, you add 1 to every numerator, and you add the number of possible values of that feature to the denominator. For the flavor (three possible values: ๐Ÿฏ sweet, ๐Ÿง‚ savory and ๐ŸŒถ๏ธ spicy), that becomes:

P(๐ŸŒถ๏ธ spicy | ๐Ÿ˜ Yes) = 0+14+3=17\frac{0 + 1}{4 + 3} = \frac{1}{7} โ‰ˆ 14%

Small, but not zero: a spicy dish still gets a low score for ๐Ÿ˜ Yes, but the other features can pull it back up. No probability is ever exactly 0% or 100% anymore. In the demo in the section below, you can switch this on and off with the "Laplace smoothing" switch.

In general, you replace the plain frequency with:

Laplace smoothing Rule

Add 1 to every count in the numerator, and the number of possible values of the feature to the denominator, so that no probability is ever exactly 0.

P(valueโˆฃlabel)=numberย ofย examplesย withย thisย labelย andย thisย value+1numberย ofย examplesย withย thisย label+numberย ofย possibleย valuesย ofย theย featureP(\text{value} \mid \text{label}) = \frac{\text{number of examples with this label and this value} + 1}{\text{number of examples with this label} + \text{number of possible values of the feature}}

Because you add the number of possible values to the denominator, the probabilities of all values of a feature still add up neatly to 1.

๐Ÿ‹๏ธ Practice

In the naive Bayes demo below, you can load different datasets. Above the table you choose the dataset, in the "Test data point" row you put together the new data point, and to the right of it you see the predicted label. Below that come the three steps from this chapter (the prior probabilities, the probability of each feature given the label, and the scores), plus the conversion to percentages. Click a probability in step 1 or 2 and the table lights up the rows that were counted.

Loading demo

Try the following exercises:

1. โœ๏ธ Who wrote the pamphlet? A historian has ten Dutch-language pamphlets whose author is known (๐Ÿ–‹๏ธ Adriaan or ๐Ÿชถ Barbara), with three stylistic features: does the text use the word "nochtans" (Dutch for "nevertheless"), does it use "evenwel" ("however"), and are the sentences long or short? A new, anonymous pamphlet contains both "nochtans" and "evenwel" and has long sentences. First calculate the two scores yourself on paper (three steps: prior probabilities, probabilities per feature, multiplying), and then check whether the demo says the same.

Solution

2. ๐Ÿ‘• Does someone buy the T-shirt? Calculate for yourself whether a customer buys a blue, medium, basic T-shirt, and then compare with the intermediate steps in the demo.

3. ๐Ÿฅ Quick triage. This dataset has three labels: ๐ŸŸข OK, ๐ŸŸ  Follow up and ๐Ÿ”ด Refer. Calculate the three scores for the example patient (fever, cough, no fatigue, heart rate 90-99). Treat each label as a separate class with its own prior probability and its own probabilities per feature, and do not split the question into "follow up or not". Not sure? Then switch on the Race view: each label gets its own bar that starts at its prior probability, and with the right-arrow button ("Next feature") you see the three calculations run side by side, step by step.

Solution

4. ๐Ÿ“ง Is this spam? Choose the features of a test email so that it is classified as spam with 100% certainty. Then try to get to 0% spam with as few changes as possible. Which features weigh the most?

5. โœ๏ธ Change the dataset. Click the pencil icon next to the dataset selector to edit a dataset, load the picky eater and change a few dishes. Does the prediction for the new dish change the way you expect?

6. ๐Ÿฉน Smoothing. In "Does someone buy the T-shirt?", choose a โšช white shirt. No customer ever bought a white shirt, so P(โšช white | โœ… Buys) = 0 and the score for "buys" is 0, whatever the size or fit. Now switch on Laplace smoothing (the switch at the top right of the "Formula & calculation" card) and look at how the probabilities change: no probability is exactly 0% or 100% anymore.

๐ŸŽš๏ธ From probability to decision

Like many other AI models, naive Bayes gives you not a label but a probability: "this email is spam with a probability of 85%", "there is a 72% chance that you will like this movie". A system has to do something with that: move the email to the spam folder or not, recommend the movie or not. For that, you choose a threshold: above the threshold you choose one label, below it the other.

With two labels and a threshold of 50%, that comes down to "choose the label with the highest probability", exactly what we have done so far. But nothing forces you to take 50%. In the demo below, a spam filter has calculated the probability of spam for a series of test emails, and the column "๐Ÿท๏ธ Actual" shows what the right label was. Green rows are classified correctly, red ones wrongly, and the orange line is the threshold. Move it and try to make as few mistakes as possible on this test data.

Loading demo

You will notice that you rarely get rid of all mistakes: if you move the threshold down, you catch more spam, but genuine emails also end up in the spam folder. If you move it up, the opposite happens. So a classification model can make two kinds of mistakes. The label that the system is looking for (here, spam) is called the positive label: a genuine email in the spam folder is a false positive (FP), and spam that ends up in your inbox is a false negative (FN). Those two mistakes are rarely equally bad, and the threshold is the knob with which you set the balance between them. You learn how to count those mistakes and weigh them against each other, with a confusion matrix and measures such as precision and recall, in the chapter on model evaluation.

โš–๏ธ Strengths and limitations

๐Ÿ’ช Strengths

๐Ÿšจ Limitations

  • ๐Ÿ”— The independence assumption: the biggest limitation. In reality, features are often related: "free" and "click here" occur together in spam, fever and headache occur together with the flu. Naive Bayes counts them as separate pieces of evidence, so they weigh in twice and the probability of spam or flu is overestimated.
  • ๐Ÿ“ Overconfident probabilities: because of that same double counting, the percentages of naive Bayes are often too extreme. The model says "99% sure it is spam" where 70% would be more realistic. The choice of label is usually right, but the probabilities are poorly calibrated. Do not trust them blindly.
  • ๐Ÿ”ค Only categorical features: the basic version works with a limited list of values. For numbers such as temperature or price, you have to divide the values into intervals (like the heart rate in the triage dataset) or assume a probability distribution such as the normal distribution.
  • ๐Ÿ•ณ๏ธ Zero probabilities: a value that never occurred with a label makes the whole score 0. Smoothing fixes that.
  • ๐Ÿคน Order and combinations: naive Bayes only sees which features are present, not in which order or combination. "Not good" and "good" contain the same word, and the sarcastic tweet "Great, another hour of delay" contains a positive word.

๐ŸŒ Where do you come across it?

  • ๐Ÿ“ง Spam filters: the textbook example. After Paul Graham's essay A Plan for Spam (external link) (2002), spam filters such as the ones in Mozilla Thunderbird and SpamAssassin counted, for each word, how often it occurs in spam and in ordinary email, and combined those probabilities, essentially as in this chapter.
  • โœ๏ธ Authorship attribution: in 1963, the statisticians Frederick Mosteller and David Wallace investigated which of Alexander Hamilton and James Madison had written twelve disputed Federalist Papers (external link) (1787-1788). They counted inconspicuous function words such as "upon" (typical of Hamilton) and "whilst" (typical of Madison) in the essays whose author was known, combined those probabilities with Bayes' theorem, and attributed all twelve essays to Madison. Present-day stylometry still works this way: from attributing anonymous pamphlets to unmasking pseudonyms.
  • ๐Ÿฉบ Medical diagnosis: one of the first successful medical AI systems was a naive Bayes classifier for acute abdominal pain that, based on symptoms and test results, made the right diagnosis more often than experienced doctors.
  • ๐Ÿ˜Š Sentiment analysis and language identification: is this review positive or negative? In which language is this text written? Here too, naive Bayes is often the first, surprisingly strong baseline against which researchers compare heavier models.

๐Ÿงญ When to use it?

Naive Bayes is a good fit if you:

  • ๐Ÿ“ want to classify text (spam, sentiment, topic, author), where the features are the words that are present,
  • ๐Ÿ“Š have many features and little data,
  • โšก want a first model fast, as a baseline or in a system that has to decide in real time,
  • ๐Ÿ” want to be able to explain why the model chose a label.

It is less suitable if:

  • ๐Ÿ–ผ๏ธ the features are strongly related, like the pixels of an image or the successive values of a time series,
  • ๐ŸŽฏ you need precise probabilities, and not just the right label,
  • ๐Ÿคน order or subtle combinations make the difference, such as negation and sarcasm in language.

๐Ÿ•น๏ธ Demos

๐Ÿ—ฃ๏ธ Feedback

Just like machine learning algorithms, we also love learning from your feedback to improve the course.

Let us know how informative and how difficult you found this chapter, and where it could be better.

How informative did you find this chapter?
Was the difficulty of this chapter right for your level of knowledge and skill? This chapter was...
Anonymous with random ID