逻辑回归得到有效roc_auc_score但绘制ROC曲线仅显示基线无AUC曲线如何解决
逻辑回归ROC曲线无显示问题排查与修复
问题原因
- 核心逻辑错误:遍历不同阈值生成对应预测结果
preds后,计算混淆矩阵时始终传入固定的默认阈值预测结果log_preds,导致每次循环得到的TPR、FPR完全一致,所有ROC点重合为单个点,无法形成可见曲线。 - 次要检查项:确认已提前导入所有依赖库:
numpy(别名np)、sklearn.metrics.confusion_matrix、matplotlib.pyplot(别名plt),缺少导入会触发报错导致无曲线输出。
修复后代码
import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix probas = lg.predict_proba(X_test)[:, 1] def get_preds(threshold, probabilities): return [1 if prob > threshold else 0 for prob in probabilities] roc_values = [] for thresh in np.linspace(0, 1, 100): preds = get_preds(thresh, probas) # 核心修改:将log_preds替换为当前阈值对应的preds tn, fp, fn, tp = confusion_matrix(y_test, preds).ravel() tpr = tp/(tp+fn) fpr = fp/(fp+tn) roc_values.append([tpr, fpr]) tpr_values, fpr_values = zip(*roc_values) fig, ax = plt.subplots(figsize=(10,7)) # 补充曲线标签便于展示AUC指标 ax.plot(fpr_values, tpr_values, label=f'ROC curve (AUC = {0.6664:.2f})') ax.plot(np.linspace(0, 1, 100), np.linspace(0, 1, 100), label='baseline', linestyle='--') plt.title('Receiver Operating Characteristic Curve', fontsize=18) plt.ylabel('TPR', fontsize=16) plt.xlabel('FPR', fontsize=16) plt.legend(fontsize=12) plt.show()
内容的提问来源于stack exchange,提问作者Shane Li
相关产品推荐
相关产品推荐

