csr_matrix.sort_indices是做什么用的?

5
我将按照以下方式创建csr_matrix:

我以如下方式创建csr_matrix:

>>> A = sparse.csr_matrix([[0, 1, 0],
                           [1, 0, 1],
                           [0, 1, 0]])
>>> A[2,:] = np.array([-1, -2, -3])

>>> A.indptr
Out[12]: array([0, 1, 3, 6], dtype=int32)
>>> A.indices
Out[13]: array([1, 0, 2, 0, 2, 1], dtype=int32)
>>> A.data
Out[14]: array([ 1,  1,  1, -1, -3, -2], dtype=int64)

现在我想交换indicesdata数组中的最后两个元素,所以我尝试如下:
>>> A.sort_indices()

然而,这并不会对我的矩阵产生任何影响。该函数的文档仅说明它对索引进行排序。

  1. 这个函数是做什么的?在什么情况下可以看到差异?
  2. 如何对indicesdata数组进行排序,以便于每一行的索引都被排序?
1个回答

2
如文档所述,A.sort_indices()会在原地对索引进行排序。但是有一个缓存:如果 A.has_sorted_indices 为True,则不会执行任何操作(该缓存从0.7.0版本开始引入)。

因此,为了看到差异,您需要手动将A.has_sorted_indices设置为False。

>>> A.has_sorted_indices, A.indices
(True, array([1, 0, 2, 0, 2, 1], dtype=int32))
>>> A.sort_indices()
>>> A.has_sorted_indices, A.indices
(True, array([1, 0, 2, 0, 2, 1], dtype=int32))
>>> A.has_sorted_indices = False
>>> A.sort_indices()
>>> A.has_sorted_indices, A.indices
(True, array([1, 0, 2, 0, 1, 2], dtype=int32))

请注意,与OP所表示的不同,在SciPy 0.19.0版本中运行 A[2, :] = [-1, -2, -3] 不再产生无序索引(这应该已经在0.14.0中修复了)。另一方面,此操作会产生一个警告:

SparseEfficiencyWarning:更改csr_matrix的稀疏性结构是昂贵的。 使用lil_matrix更有效率。

无论如何,我们可以通过其他方式轻松地产生无序索引,例如通过矩阵乘法:
>>> B = scipy.sparse.csr_matrix([[0, 1, 0], [1, 0, 1], [0, 1, 0]])
>>> C = B*B
>>> C.has_sorted_indices, C.indices
(0, array([2, 0, 1, 2, 0], dtype=int32))
>>> C.sort_indices()
>>> C.has_sorted_indices, C.indices
(True, array([0, 2, 1, 0, 2], dtype=int32))

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