0 votes
in Machine Learning by

Implement the KNN classification algorithm.

1 Answer

0 votes
by
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

iris_dataset=load_iris()

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)

kn.fit(A_train, 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

(iris_dataset["target_names"][prediction]))

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

Output:

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 Nov 29, 2019 in Machine Learning by SakshiSharma
...