You are on page 1of 2

Implement k-Nearest Neighbour algorithm to classify the iris data set.

Print both correct and


wrong predictions

In [ ]: import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix

In [ ]: # Load the iris dataset


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

In [ ]: iris.data.shape

In [ ]: print("Features:",iris.feature_names)

In [ ]: print(iris)

In [ ]: # Split the dataset into training and testing sets


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

In [ ]: # Initialize the k-nearest neighbors classifier


k = 3
knn_classifier = KNeighborsClassifier(n_neighbors=k)

# Train the classifier


knn_classifier.fit(X_train, y_train)

# Make predictions on the test data


y_pred = knn_classifier.predict(X_test)

# Calculate the accuracy of the classifier


accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)

# To print confusion matrix


print('Confusion matrix is as follows')
print(confusion_matrix(y_test,y_pred))

In [ ]: # Assume 'new_instance' is a new data point you want to classify


new_instance = np.array([[5.1, 3.5, 1.4, 0.2]]) # Example new instance

# Use the trained k-nearest neighbors classifier to predict the class of the new insta
predicted_class = knn_classifier.predict(new_instance)

# Map the predicted class label to the actual class name


predicted_class_name = iris.target_names[predicted_class[0]]

print("Predicted class for the new instance:", predicted_class_name)


In [ ]:

You might also like