Feature Likelihood Practice Problem
This data science coding problem helps you practice Naive Bayes, feature likelihood, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Naive Bayes.
- Problem ID: 193
- Problem key: 193-feature-likelihood
- URL: https://datacrack.app/solve/193-feature-likelihood
- Difficulty: medium
- Topic: Naive Bayes
- Module: Supervised Learning
Problem Statement
# 🧩 Feature Likelihood
---
### 🎯 Goal
Calculate how likely one feature value is inside one class.
---
### 📖 Introduction
A class prior tells Naive Bayes how common each class is before seeing any features.
A **feature likelihood** describes how strongly a feature supports a class. It answers:
$$
P(feature\ value \mid class)
$$
Meaning:
> Given that we already know the class, how likely is this feature value to appear?
In other words,
> The likelihood $P(feature\ value \mid class)$ answers: among training samples already known to be in this class, how often did this feature value appear?
For example, in spam detection:
$$
P("free" \mid spam)
$$
measures how often the word `"free"` appears among spam emails.
Naive Bayes uses these likelihoods as evidence to update the initial class probabilities.
---
### 💻 Task
Implement `feature_likelihood(feature_values, labels, target_value, target_class)`.
Your function should:
- Find all rows whose label is `target_class`.
- Count how many of those rows have `target_value`.
- Divide the matching count by the class count.
- Return the result rounded to 6 decimals.
- Return `0.0` if `target_class` does not occur.
---
### 📥 Input / 📤 Output
**Input:** one feature value per row, matching class labels, a feature value to check, and a class to condition on.
**Output:** $P(target\_value \mid target\_class)$.
---
### 🧩 Starter Code
```python
def feature_likelihood(feature_values, labels, target_value, target_class):
# Your code here
pass
```
---
### 💡 Example
```python
feature_likelihood(
["free", "meeting", "free", "free", "meeting"],
["spam", "ham", "spam", "spam", "ham"],
"free",
"spam"
)
```
Expected output: `1.0`
---
### ⚠️ Common Mistakes
- Dividing by the full dataset size instead of the class count.
- Counting the target value in rows from other classes.
- Confusing $P(value\mid class)$ with $P(class\mid value)$.
Starter Code
def feature_likelihood(feature_values, labels, target_value, target_class):
# Your code here
pass