Mean and Variance per Class Practice Problem
This data science coding problem helps you practice Gaussian Naive Bayes, mean and variance per class, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Gaussian Naive Bayes.
- Problem ID: 201
- Problem key: 201-mean-and-variance-per-class
- URL: https://datacrack.app/solve/201-mean-and-variance-per-class
- Difficulty: easy
- Topic: Gaussian Naive Bayes
- Module: Supervised Learning
Problem Statement
# 🧩 Mean and Variance per Class
---
### 🎯 Goal
Calculate the mean and population variance of each numeric feature inside each class.
---
### 📖 Introduction
Categorical Naive Bayes learned likelihood tables by counting values such as `red` or `small`.
Gaussian Naive Bayes works with continuous numeric features, so exact counting is not useful. A value like `5.72` may appear only once.
Instead, Gaussian Naive Bayes stores two parameters for every feature inside every class:
- **Mean:** the average value of that feature inside the class.
- **Variance:** how spread out those values are.
This replaces categorical likelihood tables.
Population variance is used here:
$$
Variance = \frac{\sum (x_i - \text{mean})^2}{n}
$$
where $x_i$ is one value and $n$ is the number of values in that class.
Population variance is used here because Gaussian Naive Bayes treats the training rows inside each class as the values used to estimate the class distribution. This also matches the simpler implementation used by many ML libraries.
---
### 💻 Task
Implement `mean_variance_per_class(X, y)`.
Your function should:
- Group rows by class label.
- Calculate one mean per feature for each class.
- Calculate one population variance per feature for each class.
- Return rounded means and variances to 6 decimals.
- Return `{}` when there are no rows.
---
### 📥 Input / 📤 Output
**Input:** numeric feature matrix `X` and class labels `y`.
**Output:**
```python
{
class_label: {
"means": [...],
"variances": [...]
}
}
```
---
### 🧩 Starter Code
```python
def mean_variance_per_class(X, y):
# Your code here
pass
```
---
### 💡 Example
```python
mean_variance_per_class(
[
[1, 2],
[2, 4],
[5, 8],
[7, 10],
],
["A", "A", "B", "B"]
)
```
Expected output:
```python
{
"A": {"means": [1.5, 3.0], "variances": [0.25, 1.0]},
"B": {"means": [6.0, 9.0], "variances": [1.0, 1.0]}
}
```
---
### ⚠️ Common Mistakes
- Using sample variance and dividing by `n - 1`.
- Mixing rows from different classes.
- Returning one mean per class instead of one mean per feature.
- Building categorical count tables instead of Gaussian parameters.
Starter Code
def mean_variance_per_class(X, y):
# Your code here
pass