python画P-R曲线,并计算AUPR值-实战代码

def draw_PR(dictNameYtruePred,title=None,savePath = ‘./picture/’,dpi = 600):
”’
:param dictNameYtruePred:
:param title:
:param savePath:
:param dpi:
#输入实例
# label = [1, 1, 0, 0,0,0,0, ] # y 是 a的值,x是各个元素的索引
# probability = [0.8, 0.3, 0.1, 0.2,0.3,0.4,0.6,]
# draw_PR({‘name’: [label, probability]})
”’
colors = cycle([‘sienna’,’seagreen’,’blue’, ‘red’, ‘darkorange’, ‘gold’, ‘orchid’, ‘gray’])
plt.figure() # 指定大小分辨率等,相当于画纸
for toolsName,y_trueANDpred_proba ,color in zip(dictNameYtruePred.keys(),dictNameYtruePred.values(),colors):
precision, recall, thresholds = precision_recall_curve(y_trueANDpred_proba[0], y_trueANDpred_proba[1], pos_label=1)
aupr = auc( recall,precision)#计算面积的
plt.plot(precision, recall, color=color, label=str(toolsName)+'(AUPR = %0.3f)’ % aupr, linestyle=’–‘, LineWidth=3)#横纵坐标的取值,颜色样式等

plt.xlim([-0.05, 1.05])#x坐标轴
plt.ylim([-0.05, 1.05])#y坐标轴
plt.xlabel(‘Recall’, size=25)#x标签
plt.ylabel(‘Precision’, size=25)#y标签
plt.legend(loc=”lower right”, ncol=1, fontsize=22)#加上图例
plt.title(title, size=25)
if not os.path.exists(savePath):
os.makedirs(savePath)
plt.savefig(savePath+str(1), dpi=dpi)
plt.show()
if __name__ == ‘__main__’:
label1 = [1,1, 1, 1, 1,1,1 ,1,1,0, 0, 0, 0, 0, ]
probability1 = [0.1,0.8, 0.3, 0.1, 0.6,0.5,0.8,0.9,0.4 ,0.2,0.3,0.4,0.6,0.1]
label2 = [1, 1, 1, 1,1,1 ,1,1,0, 0, 0, 0, 0, 0,0,]
probability2 = [0.9, 0.3, 0.8, 0.6,0.5,0.8,0.9,0.4 ,0.2,0.3,0.4,0.6,0.1,0.3,0.9]
draw_PR({‘name1’: [label1, probability1],
‘name2’: [label2, probability2]

})
结果:因为数据量较少,所以显示的粗糙

%title插图%num