Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 55

Calculating Posterior Probabilities with Naive Bayes

Welcome back. In our last lesson, we explored our first supervised classification algorithm, K-Nearest Neighbors (KNN). We saw that it classifies new data by taking a "vote" among its closest neighbors, a process entirely dependent on calculating distances. This approach is intuitive and powerful, but it's also "lazy"—it doesn't build an explicit model of the data.

Today, we delve into a fundamentally different method you've identified as a "great algorithm to learn": the Naive Bayes Classifier. Instead of relying on distance, this algorithm is rooted in probability theory, specifically Bayes' theorem. It builds an "eager" model by learning the probabilistic relationships between features and classes from the training data. Your goal to understand how to match with is precisely what we will be doing today. The learning outcome for this lesson is to calculate the posterior class probabilities for a new data point using a Naive Bayes classifier.

From Bayes' Theorem to Naive Bayes Classifier

As a statistician, you are well acquainted with Bayes' theorem, which describes the probability of an event based on prior knowledge of conditions that might be related to the event. In its classic form, it's expressed as:

Where:

  • is the hypothesis.
  • is the evidence.
  • is the posterior probability: the probability of the hypothesis given the evidence.
  • is the likelihood: the probability of observing the evidence given the hypothesis is true.
  • is the prior probability: the initial probability of the hypothesis.
  • is the marginal probability of the evidence.

In classification, our "hypothesis" is the class label, and our "evidence" is the set of features for a given data point. So, we can rewrite the theorem as:

To classify a new data point, we calculate this posterior probability for every possible class. The class that yields the highest posterior probability is our prediction.

The denominator, , is the same for all classes, so it acts as a normalizing constant. For classification, we often only need to compare the numerators:

The "Naive" Assumption of Independence

Here is where the "naive" part comes in. Calculating directly is difficult, as it involves the joint probability of all features. The Naive Bayes algorithm simplifies this by making a strong assumption: all features are conditionally independent of each other, given the class.

This means if our features are , the algorithm assumes:

This assumption is rarely true in the real world (e.g., a person's height and weight are not independent), but the algorithm is surprisingly effective regardless. This simplification makes the calculations computationally efficient and robust, especially with small datasets.

Our final formula for comparison becomes:

To perform a calculation, we first need to derive the prior and likelihood probabilities from our training data by creating frequency and likelihood tables.

This image illustrates the initial data processing steps for Naive Bayes. Raw data (left) is first summarized into a Frequency Table (middle) by counting occurrences. This is then used to create a Likelihood Table (right), which contains the conditional probabilities needed for the algorithm.

Let's apply this step-by-step.



Application 1: Predicting Bra Fit Complaints

Your bra-fitting business has logged data on past fittings, noting the bra's features and whether the client later filed a fit complaint (e.g., "straps digging in," "underwire poking"). You want to build a model to flag new bra-style combinations that are at high risk for a complaint.

  • Features: Underwire (Metal, Plastic), Strap (Wide, Thin)
  • Class: Complaint (Yes, No)
  • Training Data (14 clients):
Client Underwire Strap Complaint
1 Metal Wide No
2 Plastic Wide No
3 Plastic Wide No
4 Metal Wide No
5 Metal Thin Yes
6 Plastic Wide No
7 Metal Thin Yes
8 Metal Wide No
9 Plastic Thin Yes
10 Plastic Thin No
11 Plastic Thin No
12 Metal Thin Yes
13 Metal Wide Yes
14 Metal Wide No

New Data Point: You are considering a new bra style with Underwire = Metal and Strap = Thin. Should you anticipate a complaint?

Step 1: Calculate Prior Probabilities
First, we find the overall probability of a complaint.

  • Total clients = 14
  • Number of 'Yes' complaints = 5
  • Number of 'No' complaints = 9

Step 2: Calculate Likelihoods
Next, we calculate the conditional probability of each feature for our new data point (Underwire=Metal, Strap=Thin), given each class.

  • Likelihoods for Complaint=Yes (5 cases):

    • Cases with 'Yes': {M/T, M/T, P/T, M/T, M/W}
    • P(\text{Underwire=Metal} | \text{Yes}) = \frac{\text{Count(Metal & Yes)}}{\text{Count(Yes)}} = \frac{4}{5} = 0.80
    • P(\text{Strap=Thin} | \text{Yes}) = \frac{\text{Count(Thin & Yes)}}{\text{Count(Yes)}} = \frac{3}{5} = 0.60
  • Likelihoods for Complaint=No (9 cases):

    • Cases with 'No': {M/W, P/W, P/W, M/W, P/W, M/W, P/T, P/T, M/W}
    • P(\text{Underwire=Metal} | \text{No}) = \frac{\text{Count(Metal & No)}}{\text{Count(No)}} = \frac{4}{9} \approx 0.444
    • P(\text{Strap=Thin} | \text{No}) = \frac{\text{Count(Thin & No)}}{\text{Count(No)}} = \frac{2}{9} \approx 0.222

Step 3: Calculate Posterior Probabilities (Proportional)
Now we multiply the prior by the likelihoods for each class.

  • For Complaint=Yes:

  • For Complaint=No:

Since , the model predicts the class Complaint=Yes.

Step 4: Normalize to get Final Probabilities
To get the final probabilities, we normalize these values so they sum to 1.

  • Sum of proportional posteriors =
  • or 73.1%
  • or 26.9%

Conclusion: The model is 73.1% confident that this bra style will lead to a complaint. This provides a quantitative warning, suggesting you should be extra careful with fitting or perhaps choose an alternative style.



Application 2: Predicting Relationship Conflict

In her "vee" polyamorous relationship, Sarah tracks weekly dynamics to better manage harmony. She logs two key factors and whether the week was characterized by conflict.

  • Features: Communication (Direct, Indirect), Hobby (Shared, Separate)
  • Class: Conflict (Yes, No)
  • Training Data (15 weeks):
Week Communication Hobby Conflict
1 Direct Shared No
2 Indirect Shared No
3 Indirect Separate Yes
4 Direct Shared No
5 Direct Separate Yes
6 Direct Shared No
7 Indirect Shared No
8 Indirect Separate Yes
9 Indirect Shared No
10 Direct Separate Yes
11 Direct Shared No
12 Indirect Separate Yes
13 Direct Shared No
14 Direct Shared No
15 Indirect Shared No

New Data Point: The upcoming week's forecast is Communication = Direct and Hobby = Separate. Is conflict likely?

Step 1: Calculate Prior Probabilities

  • Total weeks = 15
  • Number of 'Yes' conflicts = 5
  • Number of 'No' conflicts = 10

Step 2: Calculate Likelihoods & The Zero-Frequency Problem
Let's try to calculate the likelihoods for our new data point (Comm=Direct, Hobby=Separate).

  • Likelihoods for Conflict=Yes (5 cases):

    • Cases: {I/Sep, D/Sep, I/Sep, D/Sep, I/Sep}
  • Likelihoods for Conflict=No (10 cases):

    • Cases: {D/S, I/S, D/S, D/S, I/S, I/S, D/S, D/S, D/S, I/S}

We have a problem. Because the combination Hobby=Separate never occurred in a Conflict=No week, its likelihood is zero. This will cause the entire posterior probability for the No class to become zero, regardless of the other probabilities. This is an overly confident and brittle conclusion.

Solution: Laplace (Add-1) Smoothing
To handle this, we use Laplace smoothing. We add 1 to the numerator and add k (the number of unique values for that feature) to the denominator. This prevents any probability from being exactly zero.

Here, k = 2 for both Communication (Direct, Indirect) and Hobby (Shared, Separate).

Step 2 (Revised): Smoothed Likelihoods

  • Smoothed Likelihoods for Conflict=Yes: (Denominator = count(Yes) + k = 5 + 2 = 7)

  • Smoothed Likelihoods for Conflict=No: (Denominator = count(No) + k = 10 + 2 = 12)

Step 3 (Revised): Calculate Posterior Probabilities (Proportional)

  • For Conflict=Yes:

  • For Conflict=No:

Since , the model still predicts the class Conflict=Yes.

Step 4 (Revised): Normalize

  • Sum of proportional posteriors =
  • or 76.7%
  • or 23.3%

Conclusion: After accounting for the zero-frequency issue, the model is about 77% confident that the week will involve conflict. For Sarah, this probabilistic forecast is a valuable tool. It suggests that the combination of direct communication without a shared hobby is a pattern associated with friction, prompting her to perhaps schedule a shared activity or be more mindful in conversations.


Conclusion

Today, we've walked through the mechanics of the Naive Bayes classifier, translating the principles of Bayes' theorem into a practical classification tool. You've performed the hand-calculations required to predict a class and its associated probability for new data points, reinforcing your understanding of how is derived.

Key Takeaways:

  • Naive Bayes is a probabilistic classifier based on Bayes' theorem.
  • Its core is the "naive" assumption that all features are conditionally independent given the class, which simplifies the calculation of the likelihood term .
  • The classification process involves calculating priors and likelihoods from training data, multiplying them to find a value proportional to the posterior probability for each class, and selecting the class with the highest value.
  • The Zero-Frequency Problem is a practical issue where a feature value never appears with a class, and it is handled using techniques like Laplace (Add-1) smoothing.

In our last lesson, we used distance with KNN. Today, we used probability with Naive Bayes. In our next lesson, we will explore a third approach: building a model from a series of rules. We will start laying the groundwork for Decision Trees by learning to calculate metrics like Information Gain and Gini Impurity, which are used to decide the most effective way to split the data.