170. 选择使 F1 最大化的决策阈值
重要性 欺诈检测、垃圾邮件过滤和内容审核系统都会在验证数据上调整阈值,当 precision 和 recall 同等重要时,最大化 F1 是常用的默认做法。
默认的 0.5 阈值很少是最好的。在验证集上遍历阈值并最大化 F1 是选择阈值的常用方法。
编写 best_f1_threshold(y, scores)。y 是 0/1,scores 是 floats。尝试每一个不同的 score t 作为阈值,当 score >= t 时预测为 positive。F1 = 2 TP / (2 TP + FP + FN),当分母为 0 时 F1 = 0。返回最佳 F1 对应的 (t, f1) 浮点数;若有多个相同的最大 F1,返回最大的阈值。
def best_f1_threshold(y, scores)Find the threshold that maximises F1
Slide the threshold and watch F1. The best threshold is rarely 0.5 when classes overlap.
| 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, 1, 1, 0, 1], scores [0.2, 0.9, 0.4, 0.5, 0.3]
输出: (0.3, 0.857143)
示例 2
输入: y = [1, 0, 1, 0], scores = [0.9, 0.8, 0.7, 0.1]
输出: (0.7, 0.8)
示例 3
输入: y = [1, 1, 0, 0, 1, 0], scores = [0.6, 0.6, 0.6, 0.2, 0.9, 0.1]
输出: (0.6, 0.857143)
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
提示 1
遍历排序后的不同 scores;使用 boolean masks 计算 TP, FP 和 FN。
提示 2
sorted(set(...), reverse=True) 可以按从高到低的顺序给出 thresholds。
提示 3
使用 2TP / (2TP + FP + FN) 可以避免分别计算 precision 和 recall。
提示 4
在更新最佳值时使用严格的 > 判断。
常见错误
- 在预测时使用了 > 而不是 >=。
- 在测试集上选择 threshold。
- 在处理相同 F1 值时逻辑不一致。
理解思路
模型输出一个 score;你通过一个 threshold 将其转化为 yes 或 no。降低 threshold 会捕捉到更多 positives (recall 上升),但也会标记更多 negatives (precision 下降)。F1 是 precision 和 recall 的调和平均数,用于平衡两者,而最佳 threshold 通常不是 0.5。
labels 为 0, 1, 1, 0, 1,scores 为 0.2, 0.9, 0.4, 0.5, 0.3。当 t = 0.9 时,我们标记了一个 item,是一个 true positive:TP 1, FP 0, FN 2, F1 = 2 / 5 = 0.4。当 t = 0.4 时,我们标记了 0.9, 0.5 和 0.4:TP 2, FP 1, FN 1, F1 = 4 / 6 = 0.667。当 t = 0.3 时,我们又增加了一个 positive:TP 3, FP 1, FN 0, F1 = 6 / 7 = 0.857,这是最佳值。
F1(t) = 2 TP / (2 TP + FP + FN),其中 prediction score >= t;选择 F1 最大的 t。
务必在验证数据上选择 threshold,然后将其固定用于测试集和生产环境。