【问题标题】:Fast Random Permutation of Binary Array二进制数组的快速随机排列
【发布时间】:2015-08-26 12:13:44
【问题描述】:

对于我的项目,我希望快速生成固定长度的二进制数组和给定数量的 1 和 0 的随机排列。鉴于这些随机排列,我希望按元素添加它们。

我目前使用的是numpy的ndarray对象,方便逐元素添加。我目前的代码如下:

    # n is the length of the array. I want to run this across a range of 
    # n=100 to n=1000.
    row = np.zeros(n)
    # m_list is a given list of integers. I am iterating over many possible
    # combinations of possible values for m in m_list. For example, m_list
    # could equal [5, 100, 201], for n = 500.
    for m in m_list: 
        row += np.random.permutation(np.concatenate([np.ones(m), np.zeros(n - m)]))

我的问题是,有没有更快的方法来做到这一点?根据 timeit,1000000 次调用“np.random.permutation(np.concatenate([np.ones(m), np.zeros(n - m)]))”需要 49.6 秒。出于我程序的目的,我想将其减少一个数量级。谁能建议一种更快的方法来做到这一点?

谢谢!

【问题讨论】:

  • 只是好奇,python -O?

标签: arrays numpy random binary permutation


【解决方案1】:

对于我来说,在循环外分配数组的版本 使用 cProfile 更快但不多 - 8% 左右

row = np.zeros(n, dtype=np.float64)
wrk = np.zeros(n, dtype=np.float64)

for m in m_list:

    wrk[0:m] = 1.0
    wrk[m:n] = 0.0

    row += np.random.permutation(wrk)

您可以尝试就地 shuffle(wrk) 而不是从排列中返回另一个数组,但对我来说差异可以忽略不计

【讨论】:

    猜你喜欢
    • 2017-09-08
    • 2021-03-29
    • 2013-11-22
    • 2013-01-29
    • 2021-03-15
    • 1970-01-01
    • 2016-05-09
    • 2020-07-30
    • 1970-01-01
    相关资源
    最近更新 更多