numpy,用其他矩阵的行填充稀疏矩阵

numpy, fill sparse matrix with rows from other matrix

我无法确定执行以下操作的最有效方法是什么:

import numpy as np

M = 10
K = 10
ind = np.array([0,1,0,1,0,0,0,1,0,0])
full = np.random.rand(sum(ind),K)
output = np.zeros((M,K))
output[1,:] = full[0,:]
output[3,:] = full[1,:]
output[7,:] = full[2,:]

我想构建输出,它是一个稀疏矩阵,其行在密集矩阵(完整)中给出,行索引通过二进制向量指定。 理想情况下,我想避免 for-loop。那可能吗?如果没有,我正在寻找 for-loop 最有效的方法。

我需要多次执行此操作。 ind 和 full 会不断变化,因此我只是提供了一些示例值来说明。 我希望 ind 非常稀疏(最多 10%),并且 M 和 K 都是大数(10e2 - 10e3)。最终,我可能需要在 pytorch 中执行此操作,但是 numpy 的一些体面的程序已经让我走得很远了。

如果您对这个问题有一个或多个合适的类别,也请帮我找到一个更合适的问题标题。

非常感谢, 最大值

output[ind.astype(bool)] = full

通过将 ind 中的整数值转换为布尔值,您可以 boolean indexing 到 select output 中要用以下值填充的行full

4x4 数组示例:

M = 4
K = 4
ind = np.array([0,1,0,1])
full = np.random.rand(sum(ind),K)
output = np.zeros((M,K))

output[ind.astype(bool)] = full

print(output)

[[ 0.          0.          0.          0.        ]
 [ 0.32434109  0.11970721  0.57156261  0.35839647]
 [ 0.          0.          0.          0.        ]
 [ 0.66038644  0.00725318  0.68902177  0.77145089]]