160. 通过统计排序对来计算 ROC AUC
ROC AUC 有一个直观的含义:随机选择一个正样本和一个负样本;AUC 即正样本获得更高评分的概率。平局计为 0.5。
为二分类标签编写 roc_auc(y_true, scores) 函数。以 float 类型返回 AUC。如果没有正样本或没有负样本,返回 0.5。
def roc_auc(y_true, scores)ROC curve and AUC
Each threshold gives one point (false positive rate, true positive rate). Better separated classes push the curve to the top left.
| 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 = [0, 0, 1, 1], scores = [0.1, 0.2, 0.8, 0.9]
输出: 1.0
示例 2
输入: y_true = [0, 1, 0, 1], scores = [0.5, 0.5, 0.2, 0.9]
输出: 0.875
示例 3
输入: y_true = [1, 0, 1, 0, 1, 0], scores = [0.3, 0.6, 0.7, 0.2, 0.4, 0.4]
输出: 0.611111
约束条件
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
提示 1
遍历每一个 (positive, negative) 对:如果正样本的 score 更高则加 1,如果相等则加 0.5。
提示 2
除以 n_pos * n_neg。
提示 3
该方法适用于小规模输入。
常见错误
- 忽略平局(错误的实现方式)会低估那些输出粗粒度 score 的模型的 AUC。
理解思路
ROC AUC 有一个简单的含义:随机选择一个正样本和一个负样本;AUC 是正样本获得更高评分的概率。因此,你可以通过检查每一对正负样本来计算它。平局就像抛硬币一样,计为 0.5。就像一场锦标赛,每个正样本都与每个负样本对阵,然后统计胜场。
labels [1, 0, 1, 0], scores [0.8, 0.4, 0.4, 0.2]。正样本的 scores 为 0.8 和 0.4;负样本的 scores 为 0.4 和 0.2。样本对:0.8 vs 0.4 胜,0.8 vs 0.2 胜,0.4 vs 0.4 平局 (0.5),0.4 vs 0.2 胜。总计 3.5 / 4 对,所以 AUC = 0.875。AUC 为 0.5 代表随机猜测,1.0 代表完美排序。如果没有正样本或没有负样本,返回 0.5。
AUC = (wins + 0.5 x ties) / (n_pos x n_neg)。它是欺诈检测或点击率模型等排序类分类器的常用指标。
公司3
- ByteDance the topic appears in interview reports ByteDance Machine Learning Engineer Interview Process
- Google the topic appears in interview reports Google Machine Learning Engineer Interview Guide (Interview Query)
- Microsoft a candidate reported this question Microsoft Machine Learning Engineer Interview Questions | Screna AI
来自公开面试报告和指南。与这些公司无隶属关系或背书关系。