KNN on a Real Dataset Practice Problem
This data science coding problem helps you practice K-Nearest Neighbors, knn on a real dataset, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of K-Nearest Neighbors.
- Problem ID: 189
- Problem key: 189-knn-on-a-real-dataset
- URL: https://datacrack.app/solve/189-knn-on-a-real-dataset
- Difficulty: medium
- Topic: K-Nearest Neighbors
- Module: Supervised Learning
Problem Statement
# 🧩 KNN on a Real Dataset
---
### 🎯 Goal
Train and evaluate `sklearn`'s `KNeighborsClassifier` on the Iris dataset.
---
### 📖 Introduction
So far, you built KNN's pieces from scratch: distance calculation, neighbor selection, voting, choosing `k`, and feature scaling. In practice, we use a tested library implementation, but the underlying idea is the same.
This problem uses the Iris dataset: 150 flower samples from three species, described by four measurements. You will split the data, scale the features, train KNN, and measure its test accuracy.
---
### 💻 Task
Implement `evaluate_iris_knn(n_neighbors)`.
Your function should:
- Load Iris with `load_iris()`.
- Create an 80/20 train-test split using `random_state=42` and stratification.
- Standardize using the training set's mean and standard deviation.
- Train `KNeighborsClassifier(n_neighbors=n_neighbors)`.
- Predict the test set and return accuracy rounded to 6 decimals.
---
### 📥 Input / 📤 Output
**Input**
- `n_neighbors`: the KNN value of `k`.
**Output**
```python
{"accuracy": ...}
```
---
### 🧩 Starter Code
```python
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
def evaluate_iris_knn(n_neighbors):
# Load, split, scale, train, evaluate
iris = load_iris()
pass
```
---
### 💡 Example
**Input**
```python
evaluate_iris_knn(
n_neighbors=5
)
```
**Expected output**
```python
{
"accuracy": 0.933333
}
```
---
### ⚠️ Common Mistakes
- Scaling training and test sets independently.
- Fitting the scaler on the full dataset before splitting.
- Evaluating accuracy on the training data instead of the test data.
Starter Code
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
def evaluate_iris_knn(n_neighbors):
# Load, split, scale, train, evaluate
iris = load_iris()
pass