【问题标题】:TypeError with accessing to coo_matrix by index按索引访问 coo_matrix 的 TypeError
【发布时间】:2018-11-26 16:15:20
【问题描述】:

我有 coo_matrix X 和索引 trn_idx,我想通过它们访问那个 maxtrix

print (type(X  ), X.shape)
print (type(trn_idx), trn_idx.shape)

<class 'scipy.sparse.coo.coo_matrix'> (1503424, 2795253)
<class 'numpy.ndarray'> (1202739,)

这样调用:

X[trn_idx]
TypeError: only integer scalar arrays can be converted to a scalar index

无论哪种方式:

 X[trn_idx.astype(int)] #same error

如何按索引访问?

【问题讨论】:

  • X[trn_idx.astype(int)]?
  • @Divakar ops,拼写错误
  • 给我们重现问题的最小示例案例?
  • 转换为其他稀疏格式之一。 X.tocsr()[idx,:]coo 格式没有实现索引。这应该在文档中很清楚。

标签: python python-3.x numpy scipy sparse-matrix


【解决方案1】:

coo_matrix 类不支持索引。您必须将其转换为不同的稀疏格式。

这是一个小coo_matrix的例子:

In [19]: import numpy as np

In [20]: from scipy.sparse import coo_matrix

In [21]: m = coo_matrix([[0, 0, 0, 1], [2, 0, 0 ,0], [0, 0, 0, 0], [0, 3, 4, 0]])

尝试索引m 失败:

In [22]: m[0,0]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-1f78c188393f> in <module>()
----> 1 m[0,0]

TypeError: 'coo_matrix' object is not subscriptable

In [23]: idx = np.array([2, 3])

In [24]: m[idx]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-a52866a6fec6> in <module>()
----> 1 m[idx]

TypeError: only integer scalar arrays can be converted to a scalar index

如果您将m 转换为CSR 矩阵,您可以使用idx 对其进行索引:

In [25]: m.tocsr()[idx]
Out[25]: 
<2x4 sparse matrix of type '<class 'numpy.int64'>'
    with 2 stored elements in Compressed Sparse Row format>

如果你要做更多的索引,最好将新数组保存在一个变量中,并根据需要使用它:

In [26]: a = m.tocsr()

In [27]: a[idx]
Out[27]: 
<2x4 sparse matrix of type '<class 'numpy.int64'>'
    with 2 stored elements in Compressed Sparse Row format>

In [28]: a[0,0]
Out[28]: 0

【讨论】:

  • 奇怪的是 m[idx] 返回 scalar 错误,而不是 not subscriptable 错误。当m.__getitem__not found 时,not subscriptable 是我所期望的。显然两者都是由基本的 python 解释器生成的。 [][idx] 也会产生 scalar 错误。
【解决方案2】:

尝试阅读此内容。

https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.sparse.csr_matrix.todense.html

在通过索引访问之前,您需要转换为密集矩阵。
在稀疏矩阵上尝试 toarray() 方法,然后您可以通过索引访问。

【讨论】:

  • 调用这样的函数会使矩阵变大吗?
  • X.todense()[trn_idx] 导致我记忆错误
  • @Poojan,通常使用稀疏矩阵,因为密集矩阵太大而无法放入内存。调用todense() 违背了使用稀疏矩阵的目的。
  • @Rocketq 是的,它会增加矩阵的大小,因为在稀疏矩阵中只存储非零值。
  • @WarrenWeckesser 是的,但在这里我只是说明为什么使用索引访问值会导致稀疏矩阵出错。
猜你喜欢
  • 2011-12-10
  • 2023-03-12
  • 2016-08-25
  • 2021-06-11
  • 2021-02-07
  • 1970-01-01
  • 2017-07-29
  • 2017-04-23
相关资源
最近更新 更多