2013-01-23 65 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

好吧,这是在裆部一拳...谢谢! –