BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Evaluation metrics19 of 33 in topic

170. 选择使 F1 最大化的决策阈值

MediumEvaluation metrics

重要性 欺诈检测、垃圾邮件过滤和内容审核系统都会在验证数据上调整阈值,当 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)
Play with it

Find the threshold that maximises F1

Slide the threshold and watch F1. The best threshold is rarely 0.5 when classes overlap.

0102000.20.40.60.81scorecount00.250.50.75100.20.40.60.81false positive ratetrue positive rate
predicted 1predicted 0
actual 1TP 114FN 36
actual 0FP 33TN 117
precision
0.776
recall
0.76
F1
0.768
MCC
0.54
ROC AUC
0.849
class 1class 0

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。

Worked example

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,然后将其固定用于测试集和生产环境。

主题
Evaluation metrics
相似题目
  • 通过统计排序对来计算 ROC AUCMedium
  • 使用 NDCG@k 对搜索排名进行评分Medium
  • 计算多分类分类器的 macro 和 micro F1Medium
  • 使用 Cohen's kappa 衡量评分者一致性Medium
所有 Evaluation metrics 道题目
反馈
170 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def best_f1_threshold(y, scores):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 4 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS