首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >csr_matrix.sort_indices是做什么的?

csr_matrix.sort_indices是做什么的?
EN

Stack Overflow用户
提问于 2015-02-10 09:24:33
回答 1查看 3.2K关注 0票数 5

我用以下方式制作了一个csr_matrix:

代码语言:javascript
运行
复制
>>> 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数组中的最后两个元素,所以我尝试:

代码语言:javascript
运行
复制
>>> A.sort_indices()

然而,这对我的矩阵没有任何影响。此函数的手册只说明它对索引进行排序。

  1. 这个功能是做什么的?在哪种情况下你能看到不同的情况?
  2. 如何对indicesdata数组进行排序,以便对每一行索引进行排序?
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-31 05:36:32

正如文档中所述,A.sort_indices()对适当的索引进行排序.但是有一个缓存:是真的,它什么也做不了 (缓存是在0.7.0)。

因此,为了看到不同之处,需要手动将A.has_sorted_indices设置为False。

代码语言:javascript
运行
复制
>>> 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更有效。

无论如何,我们可以很容易地以其他方式产生无序索引,例如通过矩阵乘法:

代码语言:javascript
运行
复制
>>> 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))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28428063

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档