给定一个表示二维分布的二维 Numpy 数组,如何借助 Numpy 或 Scipy 函数从该分布中采样数据?

jab*_*woo 5 python arrays numpy scipy python-3.x

给定一个dist形状为 的二维 numpy 数组(200,200),其中数组的每个条目表示 (x1, x2) 对于所有 x1 , x2 的联合概率?{0, 1, . . . , 199}。如何借助 Numpy 或 Scipy API 从这个概率分布中采样双变量数据x = (x1, x2)?

app*_*496 10

该解决方案适用于任意维数的概率分布,假设它们是有效的概率分布(其内容之和必须为 1,等等)。它使分布变平,从中进行采样,并调整随机索引以匹配原始数组形状。

# Create a flat copy of the array
flat = array.flatten()

# Then, sample an index from the 1D array with the
# probability distribution from the original array
sample_index = np.random.choice(a=flat.size, p=flat)

# Take this index and adjust it so it matches the original array
adjusted_index = np.unravel_index(sample_index, array.shape)
print(adjusted_index)
Run Code Online (Sandbox Code Playgroud)

另外,要获取多个示例,请size在调用中添加关键字参数np.random.choice,并adjusted_index在打印之前进行修改:

adjusted_index = np.array(list(zip(*adjusted_index)))
Run Code Online (Sandbox Code Playgroud)

这是必要的,因为np.random.choice使用size参数会输出每个坐标维度的索引列表,因此这会将它们压缩到坐标元组列表中。这也比简单地重复第一个代码更有效


相关文档: