2011-07-27 78 views
26

我正在處理一些相當大的稀疏矩陣(從5000x5000到20000x20000),並且需要找到一種有效的方式來以靈活的方式連接矩陣,以便從單獨的部分構造隨機矩陣。是否有連接scipy.sparse矩陣的有效方法?

現在,我正在使用以下方式連接四個矩陣,但效率非常低。有沒有更好的方法來做到這一點,不涉及轉換爲密集矩陣?

rmat[0:m1.shape[0],0:m1.shape[1]] = m1 
rmat[m1.shape[0]:rmat.shape[0],m1.shape[1]:rmat.shape[1]] = m2 
rmat[0:m1.shape[0],m1.shape[1]:rmat.shape[1]] = bridge 
rmat[m1.shape[0]:rmat.shape[0],0:m1.shape[1]] = bridge.transpose() 

回答

14

好的,我找到了答案。使用scipy.sparse.coo_matrix要比使用lil_matrix快得多。我將矩陣轉換爲coo(無痛且快速),然後在添加正確的填充後將數據,行和列連接起來。

data = scipy.concatenate((m1S.data,bridgeS.data,bridgeTS.data,m2S.data)) 
rows = scipy.concatenate((m1S.row,bridgeS.row,bridgeTS.row + m1S.shape[0],m2S.row + m1S.shape[0])) 
cols = scipy.concatenate((m1S.col,bridgeS.col+ m1S.shape[1],bridgeTS.col ,m2S.col + m1S.shape[1])) 

scipy.sparse.coo_matrix((data,(rows,cols)),shape=(m1S.shape[0]+m2S.shape[0],m1S.shape[1]+m2S.shape[1])) 
+1

感謝您回覆並評論您是如何快速完成的。我需要它用於我的NLP課程。 – placeybordeaux

42

稀疏庫現在具有hstackvstack分別用於水平和垂直方向串聯矩陣。

+1

確保您使用scipy.sparse.hstack而不是numpy.hstack – 0111001101110000

9

使用hstack,vstack或concatenate比連接內部數據對象本身慢得多。原因在於,hstack/vstack將稀疏矩陣轉換爲coo格式,當矩陣非常大而非coo格式時,它可能非常緩慢。下面是串聯CSC矩陣代碼,可用於CSR矩陣類似的方法:

def concatenate_csc_matrices_by_columns(matrix1, matrix2): 
    new_data = np.concatenate((matrix1.data, matrix2.data)) 
    new_indices = np.concatenate((matrix1.indices, matrix2.indices)) 
    new_ind_ptr = matrix2.indptr + len(matrix1.data) 
    new_ind_ptr = new_ind_ptr[1:] 
    new_ind_ptr = np.concatenate((matrix1.indptr, new_ind_ptr)) 

    return csc_matrix((new_data, new_indices, new_ind_ptr)) 
+1

只是在尋找將新行追加到CSR矩陣的快速方式。這正是我需要的。謝謝@amos。 – singleton

+0

如果你使用這種方法,你需要在'return csc_matrix((new_data,new_indices,new_ind_ptr)')中指定形狀,例如:'return csc_matrix((new_data,new_indices,new_ind_ptr),shape =(matrix1.shape [1], matrix1.shape [1] + matrix2.shape [1])' – simeon

4

阿莫斯的回答不再是必要的。如果輸入矩陣採用csr或csc格式,並且所需的輸出格式設置爲無或輸入矩陣的格式相同,現在Scipy在內部執行類似於此操作的操作。以csr格式垂直堆疊矩陣或以csc格式水平堆疊矩陣是有效的,分別使用scipy.sparse.vstackscipy.sparse.hstack

+0

「now」是指哪個版本?是否有任何參考? – lenz

+0

相關代碼是[this snippet](https://github.com) /scipy/scipy/blob/master/scipy/sparse/construct.py#L552)from'scipy.sparse.bmat','vstack'和'hstack'都使用。這個hack最初被添加到[here](https: //github.com/scipy/scipy/commit/10b2cbdc980c6e1695c732c90fba99f722437171)在2013年,它看起來像它最初包含在scipy 1.0.0 –

+0

謝謝!Scipy 1.0.0仍處於RC階段,但... – lenz