2017-05-19 46 views
1

填補行稀疏矩陣我有麻煩搞清楚什麼是做的最有效的方法如下:numpy的,從其他基質

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循環。那可能嗎?如果沒有,我正在尋找最有效的方式來循環這個。

我需要執行此操作很多次。 ind和full將不斷變化,因此我只是提供了一些示例值用於說明。 我期望ind很稀少(最多10%),M和K都是很大的數字(10e2 - 10e3)。最終,我可能需要在pytorch中執行這個操作,但是對於numpy來說,一些體面的程序已經讓我頗爲滿意。

如果您有一個或多個適合此問題的類別,還請幫助我找到更適合問題的標題。

非常感謝, 最大

回答

4
output[ind.astype(bool)] = full 

通過ind轉換的整數值布爾值,你可以做boolean indexing選擇要在full與值來填充output行。

例如具有4×4陣列

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]]