Numpy重复随机选择

2024-10-04 01:33:35 发布

您现在位置:Python中文网/ 问答频道 /正文

想象一个二维布尔字段。假设它是一个a x b=3x3字段

F= [[0 1 0] [0 1 0] [1 1 1]]

without_zeros(range(9)*F) = (1 4 6 7 8 ) 这是ID列表,其中F=True

现在,我需要N=e.g.1M的可能性,从这个数字范围内随机选择m(例如3),而不重复

例如

1 7 4
4 6 8
8 6 1
1 6 4
... 

我使用矢量化函数的方法失败了

到目前为止,我最好的成绩是 a=3,b=3,N=5E6,m=3 ~84秒。在i37250上

我的问题:有没有更好的方法防止for循环并并行/矢量化工作

compiled - start timer
Time: 84.47356009483337
finish

工作示例:

import numpy as np
from numba import jit, prange
import time as t

@jit
def startzellen_zufall(mask, m, N):
    b = mask.reshape(mask.size)
    a = np.arange(1, len(b) + 1, dtype=np.int16)
    c = a * b
    clean = np.array(c[c != 0], dtype=np.int16)

    l = []
    for i in prange(0, N):
        l.append(np.random.choice(clean, m, replace=False))
    return np.stack(l)

##############
N = 5000000
m = 3
mask = np.array([[True, False, False], [False, True, True], [True, False, True]])

startzellen_zufall(mask, m, N)
print("compiled - start timer")
t1 = t.time()
startzellen_zufall(mask, m, N)
t2 = t.time()
print("Time: %s" % (t2 - t1))
print("finish")


Tags: 方法importfalsetruefortimenpmask