比较两种阵列的KNN预测精度

2024-04-26 01:03:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数组,从中我必须找到我的预测的准确性。你知道吗

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

谢谢你帮我。你知道吗


Tags: 方法代码intestforlendef情况
3条回答

如果数组中的数字在python解释器没有重新创建的特定范围内,那么您的代码应该可以工作。这是因为您使用了is,这是一种身份检查,而不是相等性检查。所以,你要检查内存地址,这些地址只在特定的数字范围内相等。因此,改用==,它将始终有效。你知道吗

要获得更具python风格的解决方案,您还可以查看列表理解:

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

您的代码提供了所需的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为例,它就是这样做的。你知道吗

相关问题 更多 >

    热门问题