0% found this document useful (0 votes)
6 views1 page

DATA SCI Ex12 KNN-correct and Wrong Predictions

The document contains Python code that implements a K-Nearest Neighbors (KNN) classifier using the Iris dataset. It loads the dataset, splits it into training and testing sets, trains the model, and then predicts the test set results. Finally, it prints the actual vs predicted values, a confusion matrix, and a classification report.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

DATA SCI Ex12 KNN-correct and Wrong Predictions

The document contains Python code that implements a K-Nearest Neighbors (KNN) classifier using the Iris dataset. It loads the dataset, splits it into training and testing sets, trains the model, and then predicts the test set results. Finally, it prints the actual vs predicted values, a confusion matrix, and a classification report.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

import numpy as np

import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report, confusion_matrix

# Load Iris dataset


iris = load_iris()
X, y = iris.data, iris.target

# Split the data into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)

# Train the KNN classifier with k=5


knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)

# Predict on the test set


y_pred = knn.predict(X_test)

# Print correct and wrong predictions


print("\n%-15s %-15s %-15s" % ("Actual", "Predicted", "Correct/Wrong"))
print("-" * 45)
for actual, predicted in zip(y_test, y_pred):
status = "Correct" if actual == predicted else "Wrong"
print(f"{actual:<15} {predicted:<15} {status:<15}")

# Print confusion matrix and classification report


print("\nConfusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test, y_pred))

You might also like