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

153. 使用 expected calibration error 衡量分类器的过度自信程度

EasyEvaluation metrics

一个模型如果说有 90% 的把握,那么它应该在 90% 的情况下是正确的。Expected calibration error (ECE) 衡量了置信度 (confidence) 与准确率 (accuracy) 之间的差距,这在根据模型的概率进行阈值处理或路由时非常重要。

编写 ece(probs, labels, n_bins)。probs 的 shape 为 (n, C),行之和为 1,labels 的 shape 为 (n,)。对于每个样本,预测结果是其对应行的 argmax(若出现平局,取最小的类别索引),置信度是该最大概率值。

将每个样本放入 bin b = min(int(conf * n_bins), n_bins - 1) 中。对于每个非空的 bin,计算 acc_b (正确预测的比例) 和 conf_b (平均置信度)。返回所有 bin 的 (count_b / n) * |acc_b - conf_b| 之和(float 类型)。

函数def ece(probs, labels, n_bins)

示例 1

probs = [[0.9, 0.1], [0.8, 0.2], [0.3, 0.7]], labels = [0, 1, 1], n_bins = 2. All three go to bin 1, mean confidence 0.8, accuracy 2/3, so ECE = |0.6667 - 0.8| = 0.1333.

示例 2

输入: probs = [[1.0, 0.0], [0.0, 1.0]], labels = [0, 1], n_bins = 10

输出: 0.0

约束条件

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 4 tests to be accepted.
提示 1

计算 conf = probs.max(1), pred = probs.argmax(1),然后使用布尔掩码遍历各个 bin。

提示 2

根据每个 bin 的样本占比进行加权。

常见错误
  • 像错误版本那样对所有 bin 进行等权重平均,会导致只有一个样本的 bin 与拥有四十个样本的 bin 具有相同的权重。
理解思路

一个经过校准 (calibrated) 的模型如果说有 80% 的把握,那么它应该在约 80% 的情况下是正确的。Expected calibration error 通过置信度对预测结果进行分组,并在每个组内比较平均置信度与实际准确率,同时根据每个组的样本占比进行加权。就像检查天气 App:在它预报降水概率为 70% 的日子里,是否真的有大约 70% 的日子下了雨?

Worked example

probs [[0.6, 0.4], [0.95, 0.05], [0.2, 0.8]], labels [0, 1, 1], n_bins = 4. 预测与置信度:class 0 置信度 0.6 (正确),class 0 置信度 0.95 (错误),class 1 置信度 0.8 (正确)。Bins: int(0.6 x 4) = 2, int(0.95 x 4) = 3, int(0.8 x 4) = 3。Bin 2: accuracy 1, confidence 0.6, gap 0.4, weight 1/3。Bin 3: accuracy 0.5, confidence 0.875, gap 0.375, weight 2/3。ECE = 0.133 + 0.25 = 0.383。

bin = min(int(conf x n_bins), n_bins - 1); ECE = sum over non-empty bins of (count / n) x |acc - conf|。这在对 LLM 或分类器的置信度进行路由或阈值处理时非常重要。
主题
Evaluation metrics
相似题目
  • 根据预测结果计算 precision, recall 和 F1Easy
  • 构建混淆矩阵Easy
  • 计算 mean reciprocal rankEasy
  • 通过 self-consistency 多数投票选择最终答案Easy
所有 Evaluation metrics 道题目
反馈
153 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def ece(probs, labels, n_bins):
# your code here
pass
​

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

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