比较两个数组以做出 KNN 预测的准确性

compare two arrays to make an accuracy of KNN prediction

我有两个数组,我必须从中找出预测的准确性。

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

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

所以在这种情况下,准确度是 = (8/10)*100 = 80%

我已经写了一个方法来完成这个任务。这是我的代码,但在这种情况下我没有得到 80% 的准确率。

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

谢谢你的帮助。

您的代码给出了您想要的 80.0,但是您应该使用 == 而不是 is,请参阅 reason

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


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

print(getAccuracy(y_test, predictions))
80.0

这是一个使用 Numpy 的实现:

import numpy as np

n = len(y_test)
100*np.sum(np.isclose(predictions, y_test))/n

或者如果您将列表转换为 numpy 数组,则

100*np.sum(predictions == y_test)/n

如果您想将 80.0 作为您示例的结果,它正在这样做。

如果数组中的数字在 python 解释器未重新创建的特定范围内,您的代码应该可以工作。这是因为您使用了 is 这是身份检查而不是相等性检查。因此,您正在检查内存地址,这些地址仅对特定范围的数字相等。因此,请改用 ==,它将始终有效。

对于更 Pythonic 的解决方案,您还可以查看列表理解:

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