要从2d数组中选择随机值,可以使用此

pool =  np.random.randint(0, 30, size=[4,5])
seln = np.random.choice(pool.reshape(-1), 3, replace=False)

print(pool)
print(seln)

>[[29  7 19 26 22]
 [26 12 14 11 14]
 [ 6  1 13 11  1]
 [ 7  3 27  1 12]]
[11 14 26]


由于np.random.choice无法处理2d对象,因此需要将pool重新整形为1d向量。因此,为了创建一个由原始2d数组中随机选择的值组成的2d数组,我不得不使用循环一次执行一行。

pool =  np.random.randint(0, 30, size=[4,5])
seln = np.empty([4,3], int)

for i in range(0, pool.shape[0]):
    seln[i] =np.random.choice(pool[i], 3, replace=False)

print('pool = ', pool)
print('seln = ', seln)

>pool =  [[ 1 11 29  4 13]
 [29  1  2  3 24]
 [ 0 25 17  2 14]
 [20 22 18  9 29]]
seln =  [[ 8 12  0]
 [ 4 19 13]
 [ 8 15 24]
 [12 12 19]]


但是,我正在寻找一种并行方法。同时处理所有行,而不是一次处理一个。

这可能吗?如果不是numpy,那么Tensorflow怎么样?

最佳答案

这是避免for循环的一种方法:

pool =  np.random.randint(0, 30, size=[4,5])
print(pool)
array([[ 4, 18,  0, 15,  9],
       [ 0,  9, 21, 26,  9],
       [16, 28, 11, 19, 24],
       [20,  6, 13,  2, 27]])

# New array shape
new_shape = (pool.shape[0],3)

# Indices where to randomly choose from
ix = np.random.choice(pool.shape[1], new_shape)
array([[0, 3, 3],
       [1, 1, 4],
       [2, 4, 4],
       [1, 2, 1]])


因此,ix的行都是一组随机索引,将从中采样pool。现在,每行根据pool的形状进行缩放,以便在展平时可以对其进行采样:

ixs = (ix.T + range(0,np.prod(pool.shape),pool.shape[1])).T
array([[ 0,  3,  3],
       [ 6,  6,  9],
       [12, 14, 14],
       [16, 17, 16]])


并且ixs可用于通过以下方式从pool进行采样:

pool.flatten()[ixs].reshape(new_shape)
array([[ 4, 15, 15],
       [ 9,  9,  9],
       [11, 24, 24],
       [ 6, 13,  6]])

关于python - 从2d数组创建另一个2d数组,该数组由从原始数组中随机选择的值(行之间不共享的值)组成,而无需使用循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53981752/

10-14 19:18
查看更多