Python 绘制 AUPR 曲线:详细步骤与代码示例
要绘制 AUPR 曲线,可以使用 Python 中的 matplotlib 库和 sklearn 库。以下是一个简单的例子:
- 首先,使用 sklearn 库中的
precision_recall_curve函数计算出精确度和召回率的值:
from sklearn.metrics import precision_recall_curve
precision, recall, thresholds = precision_recall_curve(y_true, y_scores)
其中,y_true 是真实标签,y_scores 是分类器的得分。
- 接下来,使用 matplotlib 库绘制 AUPR 曲线:
import matplotlib.pyplot as plt
plt.plot(recall, precision, color='b')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('AUPR Curve')
plt.show()
其中,recall 和 precision 是 sklearn 函数 precision_recall_curve 计算出的值。这将生成一个 AUPR 曲线,其中纵坐标是精度,横坐标是召回率。
- 最后,可以使用 sklearn 库中的
auc函数计算出 AUPR 值:
from sklearn.metrics import auc
aupr = auc(recall, precision)
其中,recall 和 precision 是 sklearn 函数 precision_recall_curve 计算出的值。aupr 是 AUPR 的值。
完整的代码示例:
from sklearn.metrics import precision_recall_curve, auc
import matplotlib.pyplot as plt
# 计算精度和召回率
precision, recall, thresholds = precision_recall_curve(y_true, y_scores)
# 绘制 AUPR 曲线
plt.plot(recall, precision, color='b')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('AUPR Curve')
plt.show()
# 计算 AUPR 值
aupr = auc(recall, precision)
print('AUPR: {:.4f}'.format(aupr))
注意:要绘制 AUPR 曲线,必须有正样本和负样本的标签才能计算出精度和召回率的值。
原文地址: https://www.cveoy.top/t/topic/lPDt 著作权归作者所有。请勿转载和采集!