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

标签 python numpy

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

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无法处理二维对象。因此,为了创建一个由原始二维数组中随机选择的值组成的二维数组,我必须使用循环一次执行一行。

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 - 从二维数组中,创建另一个由原始数组中随机选择的值(行之间不共享的值)组成的二维数组,而不使用循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53981752/

相关文章:

python - 如何通过Python API调用salt-ssh(SSHClient)

python - 从字符串数组转换时如何设置 numpy float 数组的精度?

python - 如何使用 python 导入 3d 模型/网格

python - 使用 matplotlib/numpy 进行线性回归

python - 如何根据给定的行值保留列

python - 使用 SQLalchemy 将数据从一个数据库移动到另一个备份数据库的最简单方法是什么?

python - 您如何知道哪个 pyTZ 实际上会按预期执行?

python - PIL : draw text spreading color outside

python - 对角线相同的矩阵

python - SciPy 导数函数 - 参数解析失败