169. 计算具有相同分数的 ROC 曲线点
重要性 ROC 曲线是欺诈检测、信用评估和医疗模型选择运行 threshold 的方式,而由于四舍五入或基于树的模型,分数相同(tied scores)的情况非常常见。
ROC 曲线绘制随着决策 threshold 下降时,true positive rate 相对于 false positive rate 的变化情况。分数相同(tied scores)的情况必须作为一个整体移动。
编写 roc_points(y, scores)。y 是包含至少一个 0 和一个 1 的 0/1 数组,scores 是 float 数组。使用每个不同的 score 作为 threshold,从高到低排序,当 score >= threshold 时预测为正类。返回 (fpr, tpr, thr) 作为 float 数组:第一个点是 threshold 为 inf 的 (0, 0),随后为每个不同的 score 对应一个点。
def roc_points(y, scores)The points that make a ROC curve
Sweeping the threshold from 1 to 0 walks the dot from (0, 0) to (1, 1).
| predicted 1 | predicted 0 | |
|---|---|---|
| actual 1 | TP 114 | FN 36 |
| actual 0 | FP 33 | TN 117 |
- precision
- 0.776
- recall
- 0.76
- F1
- 0.768
- MCC
- 0.54
- ROC AUC
- 0.849
Synthetic scores made in your browser: 150 per class, sigmoid of a normal value centred at ±separation / 2. AUC counts every positive and negative pair.
示例 1
输入: y [0, 0, 1, 1], scores [0.1, 0.4, 0.35, 0.8]
输出: fpr [0, 0, 0.5, 0.5, 1], tpr [0, 0.5, 0.5, 1, 1] and thr [inf, 0.8, 0.4, 0.35, 0.1]
示例 2
输入: y = [1, 0, 1, 0, 1], scores = [0.9, 0.7, 0.7, 0.7, 0.2]
输出: ([0.0, 0.0, 1.0, 1.0], [0.0, 0.333333, 0.666667, 1.0], [float('inf'), 0.9, 0.7, 0.2])
示例 3
输入: y = [0, 1, 0, 1], scores = [0.2, 0.9, 0.1, 0.8]
输出: ([0.0, 0.0, 0.0, 0.5, 1.0], [0.0, 0.5, 1.0, 1.0, 1.0], [float('inf'), 0.9, 0.8, 0.2, 0.1])
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
提示 1
降序排序,计算正样本和负样本的累积和,并仅保留每个相同分数组的最后一个索引。
提示 2
np.argsort(-s, kind='stable') 可以实现降序排序。
提示 3
np.diff(s) != 0 用于标记相同分数序列的末尾。
提示 4
务必包含最后一个索引。
常见错误
- 在相同分数的组内创建了点。
- 忘记了
(0, 0)起点。 - 在 threshold 判断时使用了 > 而不是 >=。
理解思路
分类器会给出 scores,我们必须选择一个 threshold 来判定某个样本为正类。每个 threshold 都会给出一个 true positive rate(我们捕获了多少真实正样本)和一个 false positive rate(我们错误地标记了多少负样本)。ROC 曲线绘制了从最严格的 threshold 到最宽松的 threshold 之间的所有这些点对。
y = 0, 0, 1, 1,scores 为 0.1, 0.4, 0.35, 0.8。从高到低排序为:0.8 (pos), 0.4 (neg), 0.35 (pos), 0.1 (neg)。在 threshold 0.8 时,我们捕获了 2 个正样本中的 1 个:TPR 0.5, FPR 0。在 0.4 时,一个负样本加入:FPR 0.5。在 0.35 时,TPR 变为 1。在 0.1 时,所有样本均为正类:(1, 1)。
Ties 很重要:如果三个项目的 score 都是 0.7,那么没有任何 threshold 可以将它们分开,因此它们会作为一个整体以一条对角线步进的方式进入。
对于每个不同的 threshold t (降序),TPR = TP(score >= t) / P 且 FPR = FP(score >= t) / N,从 (0, 0) 开始。
该曲线下的面积是 ROC AUC,团队通过观察曲线来选择运行点。
Shape 与数据流
scores (n,) -> sorted (n,) -> distinct thresholds (u,) -> curve (u + 1,)