154. 构建混淆矩阵
重要性 护栏分类器(Guardrail classifiers)的评估标准在于哪些错误单元格在增长,而不仅仅是准确率。
每个分类报告都始于混淆矩阵。
编写 confusion(y_true, y_pred, k)。返回一个 (k, k) 的 int 数组,其中条目 [i, j] 统计真实类别为 i 且被预测为类别 j 的样本数量。
def confusion(y_true, y_pred, k)A live confusion matrix
Every prediction falls in one of four cells. Move the threshold to see counts shift between them.
| 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
输入: confusion([0, 1, 1], [0, 0, 1], 2)
输出: [[1, 0], [1, 1]]
示例 2
输入: y_true = [0, 1, 2, 2, 1], y_pred = [0, 2, 2, 1, 1], k = 3
输出: [[1, 0, 0], [0, 1, 1], [0, 1, 1]]
示例 3
输入: y_true = [0, 0], y_pred = [0, 0], k = 3
输出: [[2, 0, 0], [0, 0, 0], [0, 0, 0]]
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
np.add.at(M, (y_true, y_pred), 1) 可以正确处理重复对。
提示 2
行是真实值,列是预测值。
提示 3
使用 np.add.at,而不是 M[a, b] += 1。
常见错误
- 交换了轴。
- 使用
M[y_true, y_pred]+= 1,这会导致丢失重复对。
理解思路
混淆矩阵是一个统计每个真实类别被预测为各个类别的次数的表格。对角线包含正确的预测,对角线之外的所有内容都是特定类型的错误。Precision、recall 和 F1 都可以从这一张表中读取。
y_true = [0, 0, 1, 2], y_pred = [0, 1, 1, 1], k = 3. Pair (0, 0) 为单元格 [0, 0] 加 1。Pair (0, 1) 为 [0, 1] 加 1。Pair (1, 1) 为 [1, 1] 加 1。Pair (2, 1) 为 [2, 1] 加 1。Result: [[1, 1, 0], [0, 1, 0], [0, 1, 0]]。
从一个 k by k 的整数零矩阵开始,对于每个样本,在单元格 [true, pred] 处加 1。行是真实类别,列是预测类别,绝不能反过来。如果进行向量化,请使用累加加法,因为普通的 fancy-index 赋值只会计算重复对一次。应用场景:每个分类报告、LLM 分类器的错误分析,以及追踪 false positives 的审核仪表板。
公司1
- Meta a candidate reported this question Timed ML screen: concept questions then classic models from scratch (Land the Lab)
来自公开面试报告和指南。与这些公司无隶属关系或背书关系。