Editor

Fix the KNN Bug

Intermediate · Fix the bug · from Python Classification: Build a Classifier with scikit-learn

From the lesson: Python Classification: Build a Classifier with scikit-learn

Your email inbox sorts messages into "spam" or "not spam." A bank flags transactions as "fraudulent" or "legitimate." A doctor classifies a tumor as "benign" or "malignant." These are all classification problems - the model predicts which category something belongs to.

Read the lesson

This KNN classifier is getting poor results because it is missing a critical step. Find and fix the bug. Print the accuracy rounded to 4 decimal places.

from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
X, y = make_classification(n_samples=200, n_features=4,
random_state=42)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
# BUG: Something is missing before KNN training
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)
predictions = knn.predict(X_test)
print(round(accuracy_score(y_test, predictions), 4))

More Classification exercises

All Python exercises · 50 practice problems · Data Science & Machine Learning quiz