KNN algorithm on iris dataset

0 votes

Hi guys can i please get some insights towards why my code isnt functioning as required. I am getting an 0 % accuracy. I believe its towards the end of the code when using append its returning None and i am not sure how to fix that. It should return something like accuracy:97%. Thank you in advance.

import csv
import random
import math
import operator
 
def handleDataset(filename, split, trainingSet=[] , testSet=[]):
    with open(filename, 'r') as csvfile:
        lines = csv.reader(csvfile)
        dataset = list(lines)
        for x in range(len(dataset)-1):
            for y in range(4):
                dataset[x][y] = float(dataset[x][y])
            if random.random() < split:
                trainingSet.append(dataset[x]) 
            else:
                testSet.append(dataset[x]) 
                    

def euclideanDistance(instance1, instance2, length): 
    distance = 0 
    for x in range(length): 
        distance += pow((instance1[x] - instance2[x]), 2) 
    return math.sqrt(distance) 
                        
    
def getKNeighbors(trainingSet, testInstance, k): 
    distances = [] 
    length = len(testInstance)-1 
    for x in range(len(trainingSet)): 
        dist = euclideanDistance(testInstance, trainingSet[x], length) 
        distances.append((trainingSet[x], dist)) 
    distances.sort(key=operator.itemgetter(1)) 
    neighbors = [] 
    for x in range(k): 
        neighbors.append(distances[x][0]) 
    return neighbors 
                              
                                
def getResponse(neighbors):
    classVotes = {}
    for x in range(len(neighbors)):
        response = neighbors[x][-1]
        if response in classVotes:
            classVotes[response] += 1
        else:
            classVotes[response] = 1
    sortedVotes = sorted(classVotes.items(), key=operator.itemgetter(1), reverse=True)
    return sortedVotes[0][0]                                            
                                            

                
def getAccuracy(testSet, predictions):
    correct = 0
    for x in range(len(testSet)):
        if testSet[x][-1] is predictions[x]:
            correct += 1
    return (correct/float(len(testSet))) * 100.0       

                

def main():
    # prepare data
    trainingSet=[]
    testSet=[]
    split = 0.67
    handleDataset(r'C:\Users\Desktop\Iris dataset\iris.txt', split, trainingSet, testSet)
    print('Train set: ' + repr(len(trainingSet)))
    print('Test set: ' + repr(len(testSet)))
    # generate predictions
    predictions=[]
    k = 3
    for x in range(len(testSet)):
        neighbors = getKNeighbors(trainingSet, testSet[x], k)
        result = getResponse(neighbors)
        predictions.append(result)
        print('> predicted=' + repr(result) + ', actual=' + repr(testSet[x][-1]))
    accuracy=getAccuracy(testSet, predictions)
    print('Accuracy: ' + repr(accuracy) + '%')

main()

output
   

Train set: 99
Test set: 51
> predicted='Iris-setosa', actual='Iris-setosa'
> predicted='Iris-setosa', actual='Iris-setosa'
> predicted='Iris-setosa', actual='Iris-setosa'
> predicted='Iris-setosa', actual='Iris-setosa'
> predicted='Iris-setosa', actual='Iris-setosa'
> predicted='Iris-setosa', actual='Iris-setosa'
> predicted='Iris-setosa', actual='Iris-setosa'
> predicted='Iris-setosa', actual='Iris-setosa'
> predicted='Iris-setosa', actual='Iris-setosa'
> predicted='Iris-setosa', actual='Iris-setosa'
> predicted='Iris-setosa', actual='Iris-setosa'
> predicted='Iris-setosa', actual='Iris-setosa'
> predicted='Iris-setosa', actual='Iris-setosa'
> predicted='Iris-setosa', actual='Iris-setosa'
> predicted='Iris-setosa', actual='Iris-setosa'
> predicted='Iris-setosa', actual='Iris-setosa'
> predicted='Iris-versicolor', actual='Iris-versicolor'
> predicted='Iris-versicolor', actual='Iris-versicolor'
> predicted='Iris-versicolor', actual='Iris-versicolor'
> predicted='Iris-versicolor', actual='Iris-versicolor'
> predicted='Iris-versicolor', actual='Iris-versicolor'
> predicted='Iris-versicolor', actual='Iris-versicolor'
> predicted='Iris-versicolor', actual='Iris-versicolor'
> predicted='Iris-virginica', actual='Iris-versicolor'
> predicted='Iris-versicolor', actual='Iris-versicolor'
> predicted='Iris-versicolor', actual='Iris-versicolor'
> predicted='Iris-versicolor', actual='Iris-versicolor'
> predicted='Iris-virginica', actual='Iris-versicolor'
> predicted='Iris-versicolor', actual='Iris-versicolor'
> predicted='Iris-versicolor', actual='Iris-versicolor'
> predicted='Iris-versicolor', actual='Iris-versicolor'
> predicted='Iris-versicolor', actual='Iris-versicolor'
> predicted='Iris-versicolor', actual='Iris-versicolor'
> predicted='Iris-versicolor', actual='Iris-versicolor'
> predicted='Iris-versicolor', actual='Iris-versicolor'
> predicted='Iris-virginica', actual='Iris-virginica'
> predicted='Iris-virginica', actual='Iris-virginica'
> predicted='Iris-virginica', actual='Iris-virginica'
> predicted='Iris-virginica', actual='Iris-virginica'
> predicted='Iris-virginica', actual='Iris-virginica'
> predicted='Iris-virginica', actual='Iris-virginica'
> predicted='Iris-virginica', actual='Iris-virginica'
> predicted='Iris-virginica', actual='Iris-virginica'
> predicted='Iris-virginica', actual='Iris-virginica'
> predicted='Iris-virginica', actual='Iris-virginica'
> predicted='Iris-virginica', actual='Iris-virginica'
> predicted='Iris-virginica', actual='Iris-virginica'
> predicted='Iris-virginica', actual='Iris-virginica'
> predicted='Iris-virginica', actual='Iris-virginica'
> predicted='Iris-virginica', actual='Iris-virginica'
> predicted='Iris-virginica', actual='Iris-virginica'
Accuracy: 0.0%
Sep 26 in Python by anonymous
• 120 points
81 views

No answer to this question. Be the first to respond.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.

Related Questions In Python

0 votes
1 answer
+1 vote
2 answers

Measuring the distance between pixels on OpenCv with Python

You can try this: Mat pts1(nPts, 1, CV_8UC2), ...READ MORE

answered Aug 24, 2018 in Python by Omkar
• 68,480 points
3,622 views
0 votes
1 answer

Difference between del, remove and pop on lists

es, remove removes the first matching value, ...READ MORE

answered Aug 1, 2018 in Python by Priyaj
• 57,300 points
72 views
0 votes
1 answer

When I create and remove files rapidly on windows using python I get WindowsError (Error 5)

Here's the short answer: disable any antivirus or ...READ MORE

answered Aug 31, 2018 in Python by charlie_brown
• 7,720 points
222 views
0 votes
1 answer

Python: how to print long text on different lines?

replace with a newline char. file.write(response.read().decode('utf-8').replace(";","\n")) In [72]: ...READ MORE

answered Sep 5, 2018 in Python by slayer
• 29,240 points
55 views
0 votes
1 answer

How to evaluate a soft Voting classifier being trained on some data

VotingClassifier does not have a best_score_ attribute. ...READ MORE

answered Sep 6, 2018 in Python by Priyaj
• 57,300 points
76 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 414 views