Search code examples
pythonarrayspython-3.xknn

compare two arrays to make an accuracy of KNN prediction


I have two arrays from which I have to find the accuracy of my prediction.

predictions = [1, 0, 0, 1, 1, 1, 0, 1, 1, 0]

     y_test = [1, 0, 0, 1, 0, 1, 0, 1, 1, 1]

so in this case, the accuracy is = (8/10)*100 = 80%

I have written a method to do this task. Here is my code, but I dont get the accuracy of 80% in this case.

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

Thanks for helping me.


Solution

  • You're code should work, if the numbers in the arrays are in a specific range that are not recreated by the python interpreter. This is because you used is which is an identity check and not an equality check. So, you are checking memory addresses, which are only equal for a specific range of numbers. So, use == instead and it will always work.

    For a more Pythonic solution you can also take a look at list comprehensions:

    assert len(predictions) == len(y_test), "Unequal arrays"
    identity = sum([p == y for p, y in zip(predictions, y_test)]) / len(predictions) * 100