in Machine Learning by
Q:

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
Click here to read more about Loan/Mortgage
Click here to read more about Insurance

Related questions

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