【问题标题】:Selecting rows in scipy sparse matrix在 scipy 稀疏矩阵中选择行
【发布时间】:2018-09-26 10:21:53
【问题描述】:

有没有办法在 scipy 稀疏矩阵中选择与某些给定索引对应的行?虚拟方法不起作用:

sparse.eye(3)[:2, :]

返回

TypeError: 'dia_matrix' object is not subscriptable

【问题讨论】:

  • thisthis 开头。尽管有些事情可能已经改变,但重要的是要了解有 7 种不同的稀疏矩阵类型并且它们的行为都不同(就某些操作而言)。然后您可以尝试例如sparse.eye(3, format='csr')[:2,:]

标签: python scipy sparse-matrix


【解决方案1】:

问这样的问题时,您应该说的不仅仅是“返回错误”。什么错误?这很重要。

但我会为你做这些工作:

In [143]: m =sparse.eye(3)
In [144]: m
Out[144]: 
<3x3 sparse matrix of type '<class 'numpy.float64'>'
    with 3 stored elements (1 diagonals) in DIAgonal format>
In [145]: m[:2,:]
...
TypeError: 'dia_matrix' object is not subscriptable

错误很严重。它告诉我们这种特殊的稀疏格式没有实现索引。对于常见的coo 格式,我们会遇到同样的错误。但是使用csr(或lil)格式,索引可以工作:

In [146]: m =sparse.eye(3, format='csr')
In [147]: m
Out[147]: 
<3x3 sparse matrix of type '<class 'numpy.float64'>'
    with 3 stored elements in Compressed Sparse Row format>
In [148]: m[:2,:]
Out[148]: 
<2x3 sparse matrix of type '<class 'numpy.float64'>'
    with 2 stored elements in Compressed Sparse Row format>
In [149]: _.A
Out[149]: 
array([[1., 0., 0.],
       [0., 1., 0.]])

在生成稀疏矩阵时,我喜欢将其显示为repr,它告诉我格式和大小。 print(m) (str) 以 coo 样式显示值。

sparse.eye 默认生成dia 格式,因为非零值都在一条对角线上。其他稀疏函数产生不同的默认格式。


dia 页面显示getrow 方法:

In [153]: sparse.eye(3).getrow(1)
Out[153]: 
<1x3 sparse matrix of type '<class 'numpy.float64'>'
    with 1 stored elements in Compressed Sparse Row format>

但请注意返回矩阵的格式 - csr,而不是 dia。这些格式具有易于相互转换的方法。一些操作为我们做了必要的转换。

【讨论】:

  • 是的,其实我不知道如何在stackoverflow中用输入和输出编写整个sn-p,我会试着弄清楚。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-26
  • 2017-03-31
  • 2023-04-10
  • 2017-07-21
  • 2011-11-28
  • 2017-07-02
相关资源
最近更新 更多