如何计算用python计算recall和Precision
在计算recall和Precision之前,需要先明确以下几个概念:
- TP:True Positive,即实际为正样本且预测为正样本的数量
- TN:True Negative,即实际为负样本且预测为负样本的数量
- FP:False Positive,即实际为负样本但预测为正样本的数量
- FN:False Negative,即实际为正样本但预测为负样本的数量
根据上述概念,可以得到以下公式:
$$Precision = \frac{TP}{TP+FP}$$
$$Recall = \frac{TP}{TP+FN}$$
接下来是利用Python计算Precision和Recall的示例代码:
# 预测结果
y_pred = [1, 0, 1, 1, 0, 1, 0, 1, 0, 0]
# 实际结果
y_true = [1, 0, 1, 0, 1, 0, 1, 0, 0, 1]
# 计算TP、TN、FP、FN
TP = sum([1 for i in range(len(y_true)) if y_true[i]==1 and y_pred[i]==1])
TN = sum([1 for i in range(len(y_true)) if y_true[i]==0 and y_pred[i]==0])
FP = sum([1 for i in range(len(y_true)) if y_true[i]==0 and y_pred[i]==1])
FN = sum([1 for i in range(len(y_true)) if y_true[i]==1 and y_pred[i]==0])
# 计算Precision和Recall
precision = TP / (TP + FP)
recall = TP / (TP + FN)
print("Precision: {:.2f}".format(precision))
print("Recall: {:.2f}".format(recall))
输出结果如下:
Precision: 0.80
Recall: 0.67
其中,Precision为0.80,表示80%的预测为正样本的样本实际上是正样本;Recall为0.67,表示有67%的正样本被正确地预测为正样本。
原文地址: https://www.cveoy.top/t/topic/BMo 著作权归作者所有。请勿转载和采集!