请问这个功能如何计算准确度?
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()
可以统计任何数字,只是判断它是真是假?
答案 0 :(得分:3)
truth
是一系列标签。 pred
是模型的预测数组。在理想情况下,truth
必须等于pred
。但是,实际上,模型的预测会有误差。因此,精确度的概念可以测量模型正确预测的数据点数。
假设这些是numpy数组,
truth == pred
返回True
和False
的布尔数组。例如:
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)
我假设truth
和pred
是NumPy数组或子类 - 而NumPy函数True
和False
被解释为1
或{{1 }}。
所以0
只会添加mean
等于truth
的出现次数,并将其除以元素数。
例如:
pred