Scipy:稀疏矩阵支持高级索引吗?

11

没问题:

>>> 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]] 的效果很好,但是我的数组太大了,这违背了我使用稀疏矩阵的初衷。我已经检查了一些稀疏矩阵相关的属性和方法,但没有找到任何关于高级索引的内容。有什么想法吗?


为什么要加上额外的一对方括号?它们是不稳定的逻辑,但 numpy 会忽略它们。除此之外,只使用一维的 fancy indexes,因为这些是矩阵,更高维度的 fancy indexing 可能会破坏你的二维矩阵。 - seberg
@seberg:上面的例子只是为了说明高级索引语法。在我的实际代码中,我需要使用高级索引在需要时调用_特定_行(即[t[1],t[5],t[6]]),而不是范围或切片。 - Noob Saibot
是的,但是添加额外的一对括号也可以被解释为t[np.array([x])]而不是t[x,],这会给个别索引添加一个额外的维度。我不会相信稀疏索引能够必然处理这种情况,因为你想要它这样做。 - seberg
1个回答

22
稀疏矩阵的索引支持非常有限,可用的内容取决于矩阵的格式。
例如:
>>> 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>

1
那么你的意思是...只有上面概述的索引方式才能起作用,而我的方法不行? - Noob Saibot
3
是的,我认为上面总结了稀疏矩阵的索引可能性。我几乎可以肯定,使用二维数组进行索引在任何格式下都不起作用,尽管我相信LIL格式将使用两个一维数组进行索引,并返回一行向量。 - Jaime
这篇关于编程的内容可能会对你有用:这个问题/答案。请注意,仅返回翻译的文本内容,不要解释它。 - drevicko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接