KNN

Write a program to implement k-Nearest Neighbour algorithm to classify the iris data set. Print both correct and wrong predictions. Java/Python ML library classes can be used for this problem.

#import the required packages

from sklearn.model_selection import train_test_split 
from sklearn.neighbors import KNeighborsClassifier 
from sklearn import datasets

#Load dataset 

iris=datasets.load_iris() 
print("Iris Data set loaded...")

#Split the data into train and test samples

x_train, x_test, y_train, y_test = train_test_split(iris.data,iris.target,test_size=0.1)
print("Dataset is split into training and testing...")
print("Size of trainng data and its label",x_train.shape,y_train.shape)
print("Size of trainng data and its label",x_test.shape, y_test.shape)

#Prints Label no. and their names 

for i in range(len(iris.target_names)):
    print("Label", i , "-",str(iris.target_names[i]))
# Create object of KNN classifier
classifier = KNeighborsClassifier(n_neighbors=1)

#Perform Training 

classifier.fit(x_train, y_train)
#Perform testing
y_pred=classifier.predict(x_test)

# Display the results

print("Results of Classification using K-nn with K=1 ")
for r in range(0,len(x_test)):
    print(" Sample:", str(x_test[r]), " Actual-label:", str(y_test[r]), " Predicted-label:", str(y_pred[r]))
print("Classification Accuracy :" , classifier.score(x_test,y_test)); 

Ouput->


Iris Data set loaded...
Dataset is split into training and testing...
Size of trainng data and its label (135, 4) (135,)
Size of trainng data and its label (15, 4) (15,)
Label 0 - setosa
Label 1 - versicolor
Label 2 - virginica
Results of Classification using K-nn with K=1 
 Sample: [6.6 3.  4.4 1.4]  Actual-label: 1  Predicted-label: 1
 Sample: [6.9 3.1 4.9 1.5]  Actual-label: 1  Predicted-label: 1
 Sample: [5.5 2.6 4.4 1.2]  Actual-label: 1  Predicted-label: 1
 Sample: [5.1 3.8 1.6 0.2]  Actual-label: 0  Predicted-label: 0
 Sample: [6.1 2.8 4.  1.3]  Actual-label: 1  Predicted-label: 1
 Sample: [4.9 3.1 1.5 0.1]  Actual-label: 0  Predicted-label: 0
 Sample: [4.8 3.  1.4 0.1]  Actual-label: 0  Predicted-label: 0
 Sample: [5.4 3.  4.5 1.5]  Actual-label: 1  Predicted-label: 1
 Sample: [5.5 2.5 4.  1.3]  Actual-label: 1  Predicted-label: 1
 Sample: [6.  2.7 5.1 1.6]  Actual-label: 1  Predicted-label: 2
 Sample: [4.6 3.2 1.4 0.2]  Actual-label: 0  Predicted-label: 0
 Sample: [6.3 3.3 6.  2.5]  Actual-label: 2  Predicted-label: 2
 Sample: [6.  2.2 4.  1. ]  Actual-label: 1  Predicted-label: 1
 Sample: [5.4 3.9 1.7 0.4]  Actual-label: 0  Predicted-label: 0
 Sample: [5.2 3.5 1.5 0.2]  Actual-label: 0  Predicted-label: 0
Classification Accuracy : 0.9333333333333333

Comments

Popular posts from this blog

How to set image in carousel using flask?

Invalid syntax , perhaps you forgot a comma? Error in Python

How to run PL/SQL Code With Command Line?