【问题标题】:fastest way to sample many random permutations of a numpy array对 numpy 数组的许多随机排列进行采样的最快方法
【发布时间】:2022-01-12 14:27:11
【问题描述】:

与许多其他 numpy/random 函数不同,numpy.random.Generator.permutation() 没有提供在单个函数调用中返回多个结果的明显方法。给定一个(1d)numpy数组x,我想对xn排列进行采样(每个长度为len(x)),并将结果作为一个形状为(n, len(x))的numpy数组。生成许多​​排列的一种简单方法是np.array([rng.permutation(x) for _ in range(n)])。这并不理想,主要是因为循环在 Python 中,而不是在已编译的 numpy 函数中。

import numpy as np

rng = np.random.default_rng(1234)
# x is big enough to not want to enumerate all permutations
x = rng.standard_normal(size=20)
n = 10000
perms = np.array([rng.permutation(x) for _ in range(n)])

我的用例是通过蛮力搜索来找到最小化特定属性的排列(构成“足够好”的搜索解决方案)。我可以使用 numpy 操作计算每个排列的感兴趣的属性,这些操作可以很好地矢量化/广播在结果排列矩阵上。事实证明,天真地生成排列矩阵是我代码中的瓶颈。有没有更好的办法?

【问题讨论】:

    标签: python numpy performance permutation


    【解决方案1】:

    您可以使用 rng.permuted 代替 rng.permutation 并将其与 np.tile 结合使用,以便多次重复 x 并独立地随机播放每个重复。方法如下:

    perms = rng.permuted(np.tile(x, n).reshape(n,x.size), axis=1)
    

    这在我的机器上比你的初始代码快大约 10 倍。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 2023-03-24
    • 2021-11-15
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    相关资源
    最近更新 更多