python - 如何阅读此 ROC 曲线并设置自定义阈值?
问题描述
使用此代码:
from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt
y_true = [1,0,0]
y_predict = [.6,.1,.1]
fpr, tpr, thresholds = metrics.roc_curve(y_true, y_predict , pos_label=1)
print(fpr)
print(tpr)
print(thresholds)
# Print ROC curve
plt.plot(fpr,tpr)
plt.show()
y_true = [1,0,0]
y_predict = [.6,.1,.6]
fpr, tpr, thresholds = metrics.roc_curve(y_true, y_predict , pos_label=1)
print(fpr)
print(tpr)
print(thresholds)
# Print ROC curve
plt.plot(fpr,tpr)
plt.show()
绘制了以下 roc 曲线:
scikit learn 设置阈值,但我想设置自定义阈值。
例如,对于值:
y_true = [1,0,0]
y_predict = [.6,.1,.6]
返回以下阈值:
[1.6 0.6 0.1]
为什么 ROC 曲线中不存在 1.6 值?在这种情况下,阈值 1.6 是否多余,因为概率范围为 0-1?可以设置自定义阈值:.3、.5、.7 以检查分类器在这种情况下的表现如何?
更新 :
from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt
y_true = [1,1,1,0]
y_predict = [.94,.87,.83,.80]
fpr, tpr, thresholds = metrics.roc_curve(y_true, y_predict , pos_label=1)
print('false positive rate:', fpr)
print('true positive rate:', tpr)
print('thresholds:', thresholds)
# Print ROC curve
plt.plot(fpr,tpr)
plt.show()
这产生了这个情节:
情节与博客中的参考情节不同,阈值也不同:
此外,使用实现的 scikit 返回的阈值metrics.roc_curve
是:thresholds: [0.94 0.83 0.8 ]
。scikit 是否应该返回与使用相同点相似的 roc 曲线?我应该自己实现 roc 曲线而不是依赖 scikit 实现,因为结果不同?
解决方案
ROC 曲线中不会出现阈值。scikit-learn 文档说:
thresholds[0] 表示没有实例被预测并且任意设置为 max(y_score) + 1
如果y_predict
contains 0.3, 0.5, 0.7
,则函数将尝试这些阈值 metrics.roc_curve
。
通常在计算ROC
曲线时遵循这些步骤
1.y_predict
降序排列。
2. 对于 中的每个概率分数(假设为 τ_i)y_predict
,如果y_predict
>= τ_i,则将该数据点视为正数。
PS:如果我们有 N 个数据点,那么我们将有 N 个阈值(如果 和 的组合y_true
是y_predict
唯一的)
3. 对于每个y_predicted
(τ_i) 值,计算 TPR 和 FPR。
N
4. 通过获取(数据点数量)TPR、FPR 对来绘制 ROC
您可以参考此博客以获取详细信息
推荐阅读
- multithreading - Spring批处理并行处理根据step1结果创建步骤
- python - 如何在 Python 构造函数中使用 *args 和 self
- python - 从 Numpy 数组中选择索引的快速方法
- ios - 视频不会内联加载
- mysql - MYSQL 获取投票结果表
- flutter - 如何修复颤振水平条形图中条形的高度
- r - 我们如何为 R 中的离散随机变量 X 找到 E(X^n)?
- macos - 如何将 Mac 上的默认 LibreSSL 设置为 homebrew 安装的那个
- facebook - Webhooks 预约 facebook
- sql - 将csv导入mysql工作台时如何跳过顶行