2

在 Numpy 中,ix_() 用于抓取矩阵的行和列,但它似乎不适用于稀疏矩阵。例如,此代码之所以有效,是因为它使用了密集矩阵:

>>> import numpy as np
>>> x = np.mat([[1,0,3],[0,4,5],[7,8,0]])
>>> print x
[[1 0 3]
 [0 4 5]
 [7 8 0]]
>>> print x[np.ix_([0,2],[0,2])]
[[1 3]
 [7 0]]

我使用 ix_() 来索引与第 0 行和第 2 行和列对应的元素,这给出了矩阵的 4 个角。

问题是 ix_ 似乎不适用于稀疏矩阵。继续前面的代码,我尝试以下操作:

>>> import scipy.sparse as sparse
>>> xspar = sparse.csr_matrix(x)
>>> print xspar
  (0, 0) 1
  (0, 2) 3
  (1, 1) 4
  (1, 2) 5
  (2, 0) 7
  (2, 1) 8
>>> print xspar[np.ix_([0,2],[0,2])]

并收到一条巨大的错误消息,说明存在此异常:

  File "C:\Python26\lib\site-packages\scipy\sparse\compressed.py", line 138, in check_format
    raise ValueError('data, indices, and indptr should be rank 1')
ValueError: data, indices, and indptr should be rank 1

我已经尝试过使用 SciPy 提供的其他稀疏矩阵格式,但它们似乎都不能与 ix_() 一起使用,尽管它们并不都引发相同的异常。

The example I gave used a matrix that wasn't very big or very sparse, but the ones I am dealing with are quite sparse and potentially very large so it doesn't seem prudent to just list off the elements one by one.

Does anyone know a (hopefully easy) way to do this sort of indexing with sparse matrices in SciPy or is this feature just not built into these sparse matrices?

4

1 回答 1

2

Try this instead:

>>> print xspar
  (0, 0) 1
  (0, 2) 3
  (1, 1) 4
  (1, 2) 5
  (2, 0) 7
  (2, 1) 8
>>> print xspar[[[0],[2]],[0,2]]
  (0, 0) 1
  (0, 2) 3
  (2, 0) 7

Note the difference with this:

>>> print xspar[[0,2],[0,2]]
  [[1 0]]
于 2010-02-25T23:38:24.040 回答