0% found this document useful (0 votes)
5 views2 pages

Q. Implement K-Nearest Neighbours Algorithm On Iris Dataset For Different Values of K. You Can Implement For K 4,5,6,7,8

Uploaded by

Bikram Karmakar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Q. Implement K-Nearest Neighbours Algorithm On Iris Dataset For Different Values of K. You Can Implement For K 4,5,6,7,8

Uploaded by

Bikram Karmakar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

KNN

Q. Implement k-Nearest Neighbours algorithm on Iris dataset for different values of k. You can
implement for k = 4,5,6,7,8.

ANS:-
# Import necessary modules
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Data loading
iris = pd.read_csv("Iris.csv")

print(iris.head(10))

# Scatter plot for SepalLengthCm vs PetalLengthCm


iris.plot(kind="scatter", x="SepalLengthCm", y="PetalLengthCm")
plt.grid()
plt.show()

# Create feature and target arrays


X = iris[["SepalLengthCm", "SepalWidthCm", "PetalLengthCm", "PetalWidthCm"]].values
y = iris["Species"].values
# Split into training and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Calculate and print accuracy for k = 3, 4, 5, 6, 7


for k in [3, 4, 5, 6, 7]:
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(X_train, y_train)
accuracy = knn.score(X_test, y_test)
print(f"Accuracy for the value of k = {k}: {accuracy:.2f}")

# Compute training and test accuracy for different values of n_neighbors


neighbors = range(1, 15)
train_accuracy = []
test_accuracy = []
for n in neighbors:
knn = KNeighborsClassifier(n_neighbors=n)
knn.fit(X_train, y_train)
train_accuracy.append(knn.score(X_train, y_train))
test_accuracy.append(knn.score(X_test, y_test))
# Plot accuracy for different n_neighbors
plt.plot(neighbors, test_accuracy, label="Testing dataset Accuracy")
plt.plot(neighbors, train_accuracy, label="Training dataset Accuracy")
plt.legend()
plt.xlabel("n_neighbors")
plt.ylabel("Accuracy")
plt.title("k-NN: Varying Number of Neighbors")
plt.show()
Output:-

You might also like