62. 为评估分数计算 bootstrap 置信区间
一个在 50 个测试任务中通过率为 62% 的 agent,实际上可能是一个通过率为 50% 或 75% 的 agent。Bootstrap 区间可以在不进行任何分布假设的情况下展示这种不确定性。
为长度为 n 的 1D array x 编写 bootstrap_ci(x, n_boot=1000, alpha=0.05, seed=0)。请严格遵循以下步骤以确保结果可复现:
1. rng = np.random.default_rng(seed).
2. idx = rng.integers(0, n, size=(n_boot, n)), 进行有放回采样。
3. means = x[idx] 沿 axis 1 的 mean。
4. 返回 (lo, hi) 作为 float 元组:np.percentile(means, 100 * alpha / 2) 和 np.percentile(means, 100 * (1 - alpha / 2)),默认使用 linear interpolation。
def bootstrap_ci(x, n_boot=1000, alpha=0.05, seed=0)示例 1
for x of all 1s every resample has mean 1, so the result is (1.0, 1.0).
示例 2
输入: x = np.ones(10)
输出: (1.0, 1.0)
示例 3
输入: x = [0.0, 0.0, 0.0, 10.0], n_boot = 200, seed = 1
输出: (0.0, 7.5)
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
提示 1
Resample the data with replacement many times, record each resample's mean, and read the interval off the spread of those means.
提示 2
Make rng = np.random.default_rng(seed), draw an index matrix of shape (n_boot, n) with rng.integers, take x[idx].mean(axis=1), then use np.percentile for the two tails.
提示 3
rng.integers excludes the upper bound, so call it as rng.integers(0, n, size=(n_boot, n)); the percentiles are 100 * alpha / 2 and 100 * (1 - alpha / 2), returned as floats.
理解思路
Bootstrap 通过对自有数据进行重采样来估计统计量的确定程度。通过多次有放回地抽取 n 个值,计算每次重采样的 mean,并将这些 mean 的百分位数作为置信区间。不需要正态分布假设。这就像通过重新洗牌已有的答案来多次运行一次小型调查。
x = [0, 1]。大小为 2 的重采样结果可以是 [0, 0], [0, 1], [1, 0] 或 [1, 1],对应的 mean 分别为 0, 0.5, 0.5, 1。因此大约四分之一的 bootstrap means 为 0,一半为 0.5,四分之一为 1,95% 的区间结果接近 (0, 1),区间较宽是因为两个点提供的信息很少。对于全为 1 的数据,每个 mean 都是 1,得到 (1.0, 1.0)。注意 rng.integers(0, n) 不包含 n,因此它覆盖了每个 index;使用 n - 1 则永远无法选中最后一个元素。
idx = rng.integers(0, n, (n_boot, n)); means = x[idx].mean(1); lo, hi = percentiles at 100 alpha / 2 and 100 (1 - alpha / 2)
Agent 评估报告通常使用 bootstrap 区间。
公司1
- Microsoft a candidate reported this question Microsoft Machine Learning Engineer Interview Questions | Screna AI
来自公开面试报告和指南。与这些公司无隶属关系或背书关系。