如何调整Bootstrap重采样代码以获取预期的列索引采样结果?
Bootstrap重采样数组索引匹配问题修复
问题背景
现有基于Scipy的Bootstrap重采样代码,索引后的输出不符合预期。需求是让索引数组i的每一行对应生成一个新的重采样样本,每个样本保留原sample的所有行维度。
当前代码
def _bootstrap_resample(sample, n_resamples=None, random_state=None): """Bootstrap resample the sample.""" n = sample.shape[-1] # bootstrap - each row is a random resample of original observations i = rng_integers(random_state, 0, n, (n_resamples, n)) resamples = sample[..., i] return resamples
输入参数
- 输入
sample数组:
[[ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19]]
- 索引数组
i:
[[0 0 0 0 0 1 1 1 1 1] [2 2 2 2 2 3 3 3 3 3]]
输出对比
预期输出
每个i的行对应一个重采样样本,样本包含原sample的所有行:
[[[ 0 0 0 0 0 1 1 1 1 1] [10 10 10 10 10 11 11 11 11 11]] [[ 2 2 2 2 2 3 3 3 3 3] [12 12 12 12 12 13 13 13 13 13]]]
实际输出
当前代码将原sample的行与i的行直接对应,不符合需求:
[[[ 0 0 0 0 0 1 1 1 1 1] [ 2 2 2 2 2 3 3 3 3 3]] [[10 10 10 10 10 11 11 11 11 11] [12 12 12 12 12 13 13 13 13 13]]]
修复方案
问题源于Numpy的索引广播机制:sample[..., i]会将sample的第一维度(原样本行)与i的第一维度(重采样次数)对齐,导致维度顺序错误。
需要调整索引维度,让每个i的行应用到sample的所有行上,再调整维度顺序。修改核心代码如下:
修改后的完整代码
def _bootstrap_resample(sample, n_resamples=None, random_state=None): """Bootstrap resample the sample.""" n = sample.shape[-1] # bootstrap - each row is a random resample of original observations i = rng_integers(random_state, 0, n, (n_resamples, n)) # 扩展sample维度并调整索引,确保每个i行应用到所有sample行,再转置维度顺序 resamples = sample[:, None, i].transpose(1, 0, 2) return resamples
代码解释
sample[:, None, i]:给sample增加一个中间维度(形状从(2,10)变为(2,1,10)),使用i索引最后一维时,广播机制会让每个i的行匹配到所有sample的行,得到形状为(2,2,10)的数组;transpose(1, 0, 2):交换前两个维度,将重采样次数维度移到第一位,最终得到预期的(2,2,10)形状。
内容的提问来源于stack exchange,提问作者Revist
相关产品推荐
相关产品推荐

