比较两个阵列以进行KNN预测的准确性



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

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

谢谢你帮我。

如果数组中的数字在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作为你的例子的结果,它就是这么做的。

您的代码给出了您想要的80.0,但是您应该使用==而不是is,请查看原因。

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

最新更新