2013-01-23 67 views
7

沒問題:Scipy:稀疏矩陣是否支持高級索引?

>>> t = np.array([[1,1,1,1,1],[2,2,2,2,2],[3,3,3,3,3],[4,4,4,4,4],[5,5,5,5,5]]) 
>>> x = np.arange(5).reshape((-1,1)); y = np.arange(5) 
>>> print (t[[x]],t[[y]]) 

大問題:

>>> s = scipy.sparse.csr_matrix(t) 
>>> print (s[[x]].toarray(),s[[y]].toarray()) 
Traceback (most recent call last): 
    File "<pyshell#22>", line 1, in <module> 
:    : 
:    : 
ValueError: data, indices, and indptr should be rank 1 

s.toarray()[[x]]的偉大工程,但違背了使用稀疏矩陣作爲我的數組是太大了我的整個目的。我已經檢查了與某些稀疏矩陣相關的屬性和方法,以查看任何引用「高級索引」的內容,但沒有任何骰子。有任何想法嗎?

+0

爲什麼你要另加一對方括號?他們是不穩定的邏輯,那種numpy恰好忽略了它的推理。除此之外,只嘗試一維花式索引,這些都是矩陣,更高維度的花式索引無論如何可能會殺死你的二維矩陣。 – seberg

+0

@seberg:上面的例子只是爲了說明[高級索引](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html)語法。在我的真實代碼中,我需要高級索引來在需要時調用_specific_ rows(即[t [1],t [5],t [6]])而不是範圍或切片。 –

+0

是的,但添加額外的對可以解釋爲't [np.array([x])]'而不是't [x,]'爲單個索引添加額外的維度。我不會相信稀疏索引來處理這種情況,只要你願意。 – seberg

回答

11

稀疏矩陣的索引支持非常有限,可用的取決於矩陣的格式。

例如:

>>> a = scipy.sparse.rand(100,100,format='coo') 
>>> a[2:5, 6:8] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: 'coo_matrix' object has no attribute '__getitem__' 

>>> a = scipy.sparse.rand(100,100,format='csc') 
>>> a[2:5, 6:8] 
<3x2 sparse matrix of type '<type 'numpy.float64'>' 
    with 0 stored elements in Compressed Sparse Column format> 

雖然

>>> a[2:5:2, 6:8:3] 
Traceback (most recent call last): 
... 
ValueError: slicing with step != 1 not supported 

還有

>>> a = scipy.sparse.rand(100,100,format='dok') 
>>> a[2:5:2, 6:8:3] 
Traceback (most recent call last): 
... 
NotImplementedError: fancy indexing supported over one axis only 
>>> a[2:5:2,1] 
<3x1 sparse matrix of type '<type 'numpy.float64'>' 
    with 0 stored elements in Dictionary Of Keys format> 

甚至

>>> a = scipy.sparse.rand(100,100,format='lil') 
>>> a[2:5:2,1] 
<2x1 sparse matrix of type '<type 'numpy.int32'>' 
    with 0 stored elements in LInked List format> 
C:\Python27\lib\site-packages\scipy\sparse\lil.py:230: SparseEfficiencyWarning: Indexing into a lil_matrix with multiple indices is slow. Pre-converting to CSC or CSR beforehand is more efficient. 
    SparseEfficiencyWarning) 
>>> a[2:5:2, 6:8:3] 
<2x1 sparse matrix of type '<type 'numpy.int32'>' 
    with 0 stored elements in LInked List format> 
+0

所以你說的是......只有上面列出的索引才能起作用,而我的方式不會呢? –

+1

@NoobSaibot是的,我認爲上面總結了稀疏矩陣的索引可能性。我幾乎可以肯定,使用二維數組索引並不適用於任何格式,但我相信LIL將爲索引取兩個一維數組,並返回一個行向量。 – Jaime

+0

好吧,這是在襠部一拳...謝謝! –