【问题标题】:Speeding up multinomial random sample in Python/NumPy在 Python/NumPy 中加速多项随机样本
【发布时间】:2019-11-12 17:08:40
【问题描述】:

我正在根据一组概率probs 上的多项分布生成一个抽奖向量,其中每个抽奖都是probs 中所选条目的索引:

import numpy as np
def sample_mult(K, probs):
    result = np.zeros(num_draws, dtype=np.int32)
    for n in xrange(K):
        draws = np.random.multinomial(1, probs)
        result[n] = np.where(draws == 1)[0][0]
    return result

这可以加速吗?一遍又一遍地调用np.random.multinomial 似乎效率低下(而且np.where 也可能很慢。)

timeitThe slowest run took 6.72 times longer than the fastest. This could mean that an intermediate result is being cached 100000 loops, best of 3: 18.9 µs per loop

【问题讨论】:

    标签: python numpy optimization scipy vectorization


    【解决方案1】:

    您可以将size 选项与np.random.multinomial 一起使用以生成随机样本行,而不是仅使用默认size=1 输出一行,然后使用.argmax(1) 模拟np.where()[0][0] 行为。

    因此,我们将有一个矢量化解决方案,就像这样 -

    result = (np.random.multinomial(1,probs,size=K)==1).argmax(1)
    

    【讨论】:

      【解决方案2】:

      “选择”的 p= 参数执行此操作(并避免 argmax):

      result = np.random.choice(len(probs), K, p=probs)
      

      【讨论】:

        猜你喜欢
        • 2012-10-14
        • 2020-09-08
        • 2012-01-31
        • 2017-09-18
        • 2018-04-05
        • 2013-01-08
        • 2020-06-10
        • 2011-09-19
        相关资源
        最近更新 更多