按索引访问coo_矩阵时出现类型错误

2024-09-30 14:28:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有coo矩阵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,)

这样称呼:

^{pr2}$

以这种方式:

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

如何通过索引访问?在


Tags: numpytype矩阵scipymatrixclasssparseprint
2条回答

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失败:

^{pr2}$

如果将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

试试看这个。在

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

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

相关问题 更多 >