用(x == y).mean()估算准确度 - 它是如何工作的?

时间:2017-07-31 14:22:03

标签: python arrays pandas numpy dataframe

请问这个功能如何计算准确度?

def accuracy_score(truth, pred):
    if len(truth) == len(pred): 
        return "Predictions have an accuracy of {:.2f}%.".format((truth == pred).mean()*100)
    else:
        return "Number of predictions does not match number of outcomes!"

# Test the 'accuracy_score' function predictions = pd.Series(np.ones(5, dtype = int)) print accuracy_score(outcomes[:5], predictions)

我不明白为什么

(truth == pred).mean()

可以统计任何数字,只是判断它是真是假?

2 个答案:

答案 0 :(得分:3)

truth是一系列标签。 pred是模型的预测数组。在理想情况下,truth必须等于pred。但是,实际上,模型的预测会有误差。因此,精确度的概念可以测量模型正确预测的数据点数。

假设这些是numpy数组,

truth == pred

返回TrueFalse的布尔数组。例如:

In [668]: x = np.array([1, 1, 2, 1])

In [669]: y = np.array([1, 2, 1, 1])

In [670]: x == y
Out[670]: array([ True, False, False,  True], dtype=bool)

现在,.mean()将计算True的数量并除以总大小,并给出准确性:

In [671]: (x == y).mean()
Out[671]: 0.5

与以下内容相同:

In [672]: (x == y).sum() / len(x == y)
Out[672]: 0.5

而且,

In [673]: (x == y).sum()
Out[673]: 2

布尔数组中True个val的数量。

答案 1 :(得分:1)

我假设truthpred是NumPy数组或子类 - 而NumPy函数TrueFalse被解释为1或{{1 }}。

所以0只会添加mean等于truth的出现次数,并将其除以元素数。

例如:

pred