Example to run KNN algorithm using python

0 votes
Can you give an example of using the KNN algorithm using pyhton? Thanks
May 8 in Machine Learning by mayank
59 views

1 answer to this question.

0 votes

Have a look at this one:

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()
X_train, X_test, y_train, y_test = train_test_split(iris_dataset["data"], iris_dataset["target"], random_state=0)
kn = KNeighborsClassifier(n_neighbors=1)
kn.fit(X_train, y_train)   
x_new = np.array([[5, 2.9, 1, 0.2]])
prediction = kn.predict(x_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(X_test, y_test)))

Have a look at this geeksforgeeks page which has given a really good explanation.

answered May 8 by Harvy

Related Questions In Machine Learning

0 votes
1 answer
0 votes
1 answer

What is KNN algorithm?

KNN which stand for K Nearest Neighbor ...READ MORE

answered May 13 in Machine Learning by Jinu
23 views
0 votes
1 answer

Features of KNN algorithm

The KNN algorithm has the following features: KNN ...READ MORE

answered May 13 in Machine Learning by Vedant
31 views
0 votes
1 answer

What is supervised learning?

Supervised learning is an aspect of machine learning ...READ MORE

answered May 8 in Data Analytics by Alok
22 views
0 votes
0 answers

What is semi-supervised machine learning?

What is semi-supervised machine learning? READ MORE

May 8 in Machine Learning by Ganesh
12 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer