152. 根据预测结果计算 precision, recall 和 F1
当某一类别非常稀有时,Accuracy 会掩盖很多问题。Precision 衡量的是被标记为正样本的项目中有多少是正确的;Recall 衡量的是所有正确的项目中有多少被你标记了出来;F1 是两者的调和平均数。
编写 prf1(y_true, y_pred) 函数,输入为二分类的 0/1 列表。返回 (precision, recall, f1)。将任何 0 / 0 的情况定义为 0.0。
def prf1(y_true, y_pred)Precision, recall and F1 as the threshold moves
Drag the threshold. Raising it trades recall for precision.
| 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_true = [1, 0, 1, 1, 0, 0, 1], y_pred = [1, 1, 0, 1, 0, 0, 0]
输出: (0.666667, 0.5, 0.571429)
示例 2
输入: y_true = [1, 0, 1], y_pred = [0, 0, 0]
输出: (0.0, 0.0, 0.0)
示例 3
输入: y_true = [0, 1, 1], y_pred = [0, 1, 1]
输出: (1.0, 1.0, 1.0)
约束条件
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
Everything comes from three counts: true positives, false positives and false negatives.
提示 2
Count tp, fp and fn by zipping the two lists, then precision = tp / (tp + fp), recall = tp / (tp + fn), and F1 = 2pr / (p + r).
提示 3
Guard every division: if the denominator is 0, return 0.0 for that value, for example pr = tp / (tp + fp) if tp + fp else 0.0.
常见错误
- 有 Bug 的版本颠倒了分母,并且使用了算术平均值。
理解思路
当正样本很稀有时,即使模型从未找回正样本,Accuracy 看起来也可能很出色。Precision 问的是:在我标记的所有内容中,有多少是正确的?Recall 问的是:在所有真正的正样本中,我标记了多少?F1 通过调和平均数将两者结合,如果其中任何一个较低,F1 也会保持在较低水平。可以把这想象成一张渔网:precision 是捕获的东西中有多少是鱼,recall 是你捕获了多少比例的鱼。
y_true = [1, 1, 0, 0, 1], y_pred = [1, 0, 0, 0, 0]. True positives = 1, false positives = 0, false negatives = 2. Precision = 1 / 1 = 1.0. Recall = 1 / 3 = 0.333. F1 = 2 x 1 x 0.333 / (1 + 0.333) = 0.5, 而算术平均值会得到 0.667。
P = TP / (TP + FP), R = TP / (TP + FN), F1 = 2PR / (P + R), 其中任何 0 / 0 都视为 0.0。这些指标是内容审核、垃圾邮件过滤和检索分类器的标准衡量指标。
公司3
- Google the topic appears in interview reports Google Interview Prep (Deep-ML)
- Meta a candidate reported this question Timed ML screen: concept questions then classic models from scratch (Land the Lab)
- Microsoft a candidate reported this question Microsoft Machine Learning Engineer Interview Questions | Screna AI
来自公开面试报告和指南。与这些公司无隶属关系或背书关系。