Gaussian Naive Bayes on a Real Dataset Practice Problem
This data science coding problem helps you practice Gaussian Naive Bayes, gaussian naive bayes on a real dataset, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Gaussian Naive Bayes.
- Problem ID: 200
- Problem key: 200-gaussian-naive-bayes-on-a-real-dataset
- URL: https://datacrack.app/solve/200-gaussian-naive-bayes-on-a-real-dataset
- Difficulty: medium
- Topic: Gaussian Naive Bayes
- Module: Supervised Learning
Problem Statement
# 🧩 Gaussian Naive Bayes on a Real Dataset
---
### 🎯 Goal
Train and evaluate sklearn's `GaussianNB` on the Iris dataset using the raw numeric features.
---
### 📖 Introduction
The previous CategoricalNB real-dataset problem had to bin Iris measurements first because `CategoricalNB` expects categorical inputs.
Gaussian Naive Bayes is different. It is designed for continuous numeric features, so Iris can be used directly.
Each class-feature pair is modeled with a mean and variance. sklearn handles those calculations inside:
```python
GaussianNB()
```
This problem connects the manual Gaussian Naive Bayes ideas to the real sklearn model.
---
### 💻 Task
Implement `gaussian_naive_bayes_on_iris(test_size=0.3, random_state=0)`.
Your function should:
- Load the Iris dataset.
- Split it into train and test sets using `stratify=y`.
- Train sklearn's `GaussianNB` directly on the numeric training features.
- Do not bin the features.
- Predict the test set.
- Return train size, test size, accuracy, the first five predicted class names, and all class names.
Round accuracy to 6 decimals.
---
### 📥 Input / 📤 Output
**Input:** `test_size` and `random_state`.
**Output:**
```python
{
"train_size": ...,
"test_size": ...,
"accuracy": ...,
"first_five_predictions": [...],
"classes": [...]
}
```
---
### 🧩 Starter Code
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
def gaussian_naive_bayes_on_iris(test_size=0.3, random_state=0):
# Your code here
pass
```
---
### 💡 Example
```python
gaussian_naive_bayes_on_iris(test_size=0.3, random_state=0)
```
Expected output:
```python
{
"train_size": 105,
"test_size": 45,
"accuracy": 0.977778,
"first_five_predictions": ["virginica", "virginica", "setosa", "setosa", "versicolor"],
"classes": ["setosa", "versicolor", "virginica"]
}
```
---
### ⚠️ Common Mistakes
- Binning the features before `GaussianNB`.
- Using `CategoricalNB` in this Gaussian topic.
- Splitting without `stratify=y`.
- Returning numeric class IDs instead of class names.
Starter Code
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
def gaussian_naive_bayes_on_iris(test_size=0.3, random_state=0):
# Your code here
pass