Class Prior Probability Practice Problem
This data science coding problem helps you practice Naive Bayes, class prior probability, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Naive Bayes.
- Problem ID: 192
- Problem key: 192-class-prior-probability
- URL: https://datacrack.app/solve/192-class-prior-probability
- Difficulty: easy
- Topic: Naive Bayes
- Module: Supervised Learning
Problem Statement
# 🧩 Class Prior Probability
---
### 🎯 Goal
Calculate how common each class is in the training data.
---
### 📖 Introduction
**Naive Bayes** is a classification algorithm that uses probabilities to decide which class best matches a new sample.
Before it looks at any feature values, Naive Bayes starts with what the training data already says about how common each class is. This starting probability is called the **class prior probability**.
For example, if `60` out of `100` training emails are spam, then the prior probability of spam is `0.6`. Before reading a new email's words, the model already knows that spam occurred 60% of the time in its training data.
---
### 💻 Task
Implement `class_priors(labels)`.
Your function should:
- Count how many times each class label appears.
- Divide each class count by the total number of labels.
- Return a dictionary mapping every observed label to its prior probability.
- Round every probability to 6 decimals.
- Return an empty dictionary when `labels` is empty.
---
### 📥 Input / 📤 Output
**Input**
- `labels`: class labels from the training dataset.
**Output**
- A dictionary where each key is a class and each value is its prior probability.
---
### 🧩 Starter Code
```python
def class_priors(labels):
# Your code here
pass
```
---
### 💡 Example
```python
class_priors(["spam", "ham", "spam", "spam", "ham"])
```
Expected output:
```python
{"spam": 0.6, "ham": 0.4}
```
---
### ⚠️ Common Mistakes
- Returning class counts instead of probabilities.
- Dividing by the count of one class instead of the total number of labels.
- Forgetting the empty-input case.
Starter Code
def class_priors(labels):
# Your code here
pass