【问题标题】:Accessing sparse matrix elements访问稀疏矩阵元素
【发布时间】:2016-08-08 18:27:49
【问题描述】:

我有一个非常大的“scipy.sparse.coo.coo_matrix”类型的稀疏矩阵。我可以使用 .tocsr() 转换为 csr,但是 .todense() 将不起作用,因为数组太大。我希望能够像处理常规数组一样从矩阵中提取元素,以便可以将行元素传递给函数。

作为参考,打印出来的矩阵如下:

(7, 0)  0.531519363001
(48, 24)    0.400946334437
(70, 6) 0.684460955022
...

【问题讨论】:

  • csr 格式接受索引,就像密集数组一样(虽然不是那么快)。 coo 格式没有。假设函数需要一个密集数组,那么对于很多人想要做的整行M1=M.tocsr(); row = M1[i,:].A (toarray())。
  • 您将如何提取例如打印顶部的三个数字((7, 0) 0.531519363001)?我不知道 .A 在您的示例中做了什么,但是如果我跳过该部分,我会得到一长排 [0 0 0 ... 0]

标签: scipy sparse-matrix


【解决方案1】:

制作一个包含 3 个元素的矩阵:

In [550]: M = sparse.coo_matrix(([.5,.4,.6],([0,1,2],[0,5,3])), shape=(5,7))

默认显示(repr(M)):

In [551]: M
Out[551]: 
<5x7 sparse matrix of type '<class 'numpy.float64'>'
    with 3 stored elements in COOrdinate format>

并打印显示 (str(M)) - 看起来像输入:

In [552]: print(M)
  (0, 0)    0.5
  (1, 5)    0.4
  (2, 3)    0.6

转换为csr格式:

In [553]: Mc=M.tocsr()
In [554]: Mc[1,:]   # row 1 is another matrix (1 row):
Out[554]: 
<1x7 sparse matrix of type '<class 'numpy.float64'>'
    with 1 stored elements in Compressed Sparse Row format>

In [555]: Mc[1,:].A    # that row as 2d array
Out[555]: array([[ 0. ,  0. ,  0. ,  0. ,  0. ,  0.4,  0. ]])

In [556]: print(Mc[1,:])    # like 2nd element of M except for row number
  (0, 5)    0.4

单个元素:

In [560]: Mc[1,5]
Out[560]: 0.40000000000000002

这些格式的数据属性(如果你想进一步挖掘)

In [562]: Mc.data
Out[562]: array([ 0.5,  0.4,  0.6])
In [563]: Mc.indices
Out[563]: array([0, 5, 3], dtype=int32)
In [564]: Mc.indptr
Out[564]: array([0, 1, 2, 3, 3, 3], dtype=int32)
In [565]: M.data
Out[565]: array([ 0.5,  0.4,  0.6])
In [566]: M.col
Out[566]: array([0, 5, 3], dtype=int32)
In [567]: M.row
Out[567]: array([0, 1, 2], dtype=int32)

【讨论】:

  • 如何提取与从 Mc[1,5] 获得的单个元素相关的两个数字(如果我没记错的话,在本例中为 (0,5))?
  • 我认为 rdist.row[i], rdist.col[i] 会得到我想要的数字。
猜你喜欢
  • 2021-12-30
  • 2013-02-13
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-05
  • 2014-12-09
相关资源
最近更新 更多