in Machine Learning by

Implement the KNN classification algorithm.

1 Answer

0 votes
We will use the Iris dataset for implementing the KNN classification algorithm.

# KNN classification algorithm

from sklearn.datasets import load_iris

from sklearn.neighbors import KNeighborsClassifier

import numpy as np

from sklearn.model_selection import train_test_split


A_train, A_test, B_train, B_test = train_test_split(iris_dataset["data"], iris_dataset["target"], random_state=0)

kn = KNeighborsClassifier(n_neighbors=1), B_train)

A_new = np.array([[8, 2.5, 1, 1.2]])

prediction = kn.predict(A_new)

print("Predicted target value: {}\n".format(prediction))

print("Predicted feature name: {}\n".format


print("Test score: {:.2f}".format(kn.score(A_test, B_test)))


Predicted Target Name: [0]

Predicted Feature Name: [‘ Setosa’]

Test Score: 0.92

Related questions

0 votes
asked Nov 29, 2019 in Machine Learning by SakshiSharma
0 votes
asked Jan 18, 2020 in Machine Learning by sharadyadav1986