mex*_*mex 2 python indexing numpy sparse-matrix slice
我很难弄清楚什么是最有效的方法来执行以下操作:
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,:]
Run Code Online (Sandbox Code Playgroud)
我想构建输出,它是一个稀疏矩阵,其行以密集矩阵(完整)给出,行索引通过二进制矢量指定。理想情况下,我想避免循环。那可能吗?如果没有,我正在寻找最有效的方法。
我需要多次执行此操作。ind和full会不断变化,因此,我仅提供了一些示例值进行说明。我希望ind相当稀疏(最多10%),M和K都很大(10e2-10e3)。最终,我可能需要在pytorch中执行此操作,但是对于numpy来说,一些不错的过程已经使我步入正轨。
如果您对此问题有一个或多个适当的类别,也请帮助我找到该问题的更适当的标题。
非常感谢,马克斯
output[ind.astype(bool)] = full
Run Code Online (Sandbox Code Playgroud)
通过将in的整数值转换ind为boolean值,您可以进行boolean索引以选择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]]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
390 次 |
| 最近记录: |