访问coo_矩阵中的元素

2024-03-28 15:07:47 发布

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

这是一个非常简单的问题。对于像coo_矩阵这样的SciPy稀疏矩阵,如何访问单个元素?

类比本征线性代数库。可以使用coeffRef访问元素(i,j),如下所示:

myMatrix.coeffRef(i,j)

Tags: 元素矩阵scipycoo本征mymatrixcoeffref
2条回答

从coo矩阵文档:

 |  Intended Usage
 |      - COO is a fast format for constructing sparse matrices
 |      - Once a matrix has been constructed, convert to CSR or
 |        CSC format for fast arithmetic and matrix vector operations
 |      - By default when converting to CSR or CSC format, duplicate (i,j)
 |        entries will be summed together.  This facilitates efficient
 |        construction of finite element matrices and the like. (see example)

实际上,csr_matrix以预期的方式支持索引:

>>> from scipy.sparse import coo_matrix
>>> m = coo_matrix([[1, 2, 3], [4, 5, 6]])
>>> m1 = m.tocsr()
>>> m1[1, 2]
6
>>> m1
<2x3 sparse matrix of type '<type 'numpy.int64'>'
    with 6 stored elements in Compressed Sparse Row format>

(我从文档中找到上述引用的方式是>>> help(m),相当于the online docs)。

为了扩展将coo矩阵转换为csr索引的过程,下面是一些小型稀疏矩阵的计时

制作矩阵

In [158]: M=sparse.coo_matrix([[0,1,2,0,0],[0,0,0,1,0],[0,1,0,0,0]])

In [159]: timeit M[1,2]
TypeError: 'coo_matrix' object is not subscriptable

In [160]: timeit M.tocsc()[1,2]
1000 loops, best of 3: 375 µs per loop

In [161]: timeit M.tocsr()[1,2]
1000 loops, best of 3: 241 µs per loop

In [162]: timeit M.todok()[1,2]
10000 loops, best of 3: 65.8 µs per loop

In [163]: timeit M.tolil()[1,2]
1000 loops, best of 3: 270 µs per loop

显然,对于选择单个元素来说,dok是最快的(计算转换时间)。这种格式实际上是一个字典,当然可以快速访问元素。

但是,如果您经常访问整行或整列,或者在行或列上迭代,则需要更仔细地阅读文档,并且可能需要对典型的数组进行自己的时间测试。

如果您正在设置值,而不仅仅是读取它们,则计时甚至实现可能会有所不同。如果尝试更改csrcsc格式的0元素,则会收到效率警告。

相关问题 更多 >