PR曲线介绍
ROC曲线介绍
代码实现
test_Y是真实值,test_Y_pred是预测值
法一:调用库函数
from sklearn.metrics import precision_recall_curve, roc_curve, roc_auc_score
import matplotlib.pyplot as plt
precision, recall, thresholds = precision_recall_curve(test_Y, test_Y_pred)
false_positive_ratio, true_positive_ratio, thresholds = roc_curve(test_Y, test_Y_pred)
# 绘制PR曲线
plt.plot(recall, precision)
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('P-R Curve')
plt.grid(True)
plt.show()
# 绘制ROC曲线
plt.plot(false_positive_ratio, true_positive_ratio)
plt.xlabel('False positive ratio')
plt.ylabel('Recall')
plt.title('ROC Curve')
plt.grid(True)
plt.show()
法二:手写
# 将预测概率值和真实标签按照预测概率值从高到低排序
sorted_index = np.argsort(test_Y_pred.flatten())[::-1]
# print(f"sort:{sorted_index}, {len(sorted_index)}")
y_pred_sorted = np.array(test_Y_pred[sorted_index])
y_true_sorted = np.array(test_Y[sorted_index])
precision = [] # 查全率,也是真正例率
recall = [] # 查准率
false_positive_ratio = [] # 假正例率
true_positive_ratio = [] # 真正例率,即查全率
tp = 0 # TP
fp = 0 # FP
tp_fn = np.sum(y_true_sorted == 1) # TP+FN
tn_fp = np.sum(y_true_sorted == 0) # TN+FP
# 以每个预测概率值为阈值
for i in range(len(y_pred_sorted)):
tp_fp = i + 1 # TP+FP
for j in range(0, tp_fp):
if y_true_sorted[j] == 1:
tp += 1
else:
fp += 1
precision_value = tp / tp_fp # 查准率precision
recall_value = tp / tp_fn # 查全率recall
false_positive = fp / tn_fp # 假正例率
true_positive = recall_value # 真正例率
precision.append(precision_value)
recall.append(recall_value)
false_positive_ratio.append(false_positive)
true_positive_ratio.append(true_positive)
tp = 0 # 这一步不要忘了!!!
fp = 0
# 绘制PR曲线
plt.plot(recall, precision)
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('P-R Curve')
plt.grid(True)
plt.show()
# 绘制ROC曲线
plt.plot(false_positive_ratio, true_positive_ratio)
plt.xlabel('False positive ratio')
plt.ylabel('True positive ratio')
plt.title('ROC Curve')
plt.grid(True)
plt.show()
两个方法画出来的图像都是一样的