2013-12-09 33 views
4

我正在使用Scipy稀疏矩陣csr_matrix作爲上下文向量在詞上下文向量。我的csr_matrix是一個(1, 300)形狀,所以它是一維向量。如何在Scipy Python Sparse Matrices中實現CSR_Matrix的循環置換(左右移位)?

我需要對稀疏向量(用於顯示左上下文和右上下文)使用置換(循環右移或循環左移)。

例如: 我有[1, 2, 3, 4],我想創造左右排列如下:

權置換:[4, 1, 2, 3]
左排列:[2, 3, 4, 1]

企業社會責任矩陣我不能訪問到列指數,所以我不能只是改變列指數。

csr_matrix中是否有任何有效的高性能行排列解決方案?或者我錯過了什麼?

可運行代碼:

from scipy.sparse import csr_matrix 
rows = [0, 0, 0] 
columns = [100, 47, 150] 
data = [-1, +1, -1] 
contextMatrix = csr_matrix((data,(rows, columns)), shape=(1, 300)) 

這意味着我有它的列100,47,150都從第0行是非零值和它們的值分別是在數據列表中的300列向量。

現在我想要的是一個排列,這意味着我想將列數組更改爲 [101,48,151]進行右置換,[99,46,149]進行左置換。

應當注意的是,排列是圓形,這意味着如果柱299具有非零數據,使用右排列的數據將被移動到列0

回答

4

您可以訪問和改變dataindices屬性的CSR矩陣,它們被存儲爲NumPy陣列。

http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html#scipy.sparse.csr_matrix

因此,使用你的代碼,按照該意見建議你可以這樣做:%the_matrix`the_matrix.indices =(the_matrix.indices + 1):

from scipy.sparse import csr_matrix 
rows = [0, 0, 0] 
columns = [100, 47, 150] 
data = [-1, +1, -1] 
m = csr_matrix((data,(rows, columns)), shape=(1, 300)) 

indices = m.indices 

# right permutation 
m.indices = (indices + 1) % m.shape[1] 

# left permutation 
m.indices = (indices - 1) % m.shape[1] 
+2

你只能說.shape [1]'我猜 – justhalf

+1

非常感謝您的幫助。我測試了它,它效果很好。 – alenrooni