从一个二维数组中,创建另一个二维数组,由原始数组中随机选择的值组成(行之间不共享的值),不使用循环。

2024-04-19 17:29:11 发布

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

要从二维数组中选择随机值,可以使用

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对象,所以需要将池重塑为一维向量。因此,为了创建一个由从原始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呢?你知道吗


Tags: 对象falsesizenprandom数组replaceprint
1条回答
网友
1楼 · 发布于 2024-04-19 17:29:11

以下是避免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]]) 

相关问题 更多 >