访问coo_matrix中的元素

har*_*nan 9 python scipy

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

给出特征线性代数库的类比.可以使用coeffRef访问元素(i,j),如下所示:

myMatrix.coeffRef(i,j)
Run Code Online (Sandbox Code Playgroud)

ev-*_*-br 24

来自coo_matrix的文档:

 |  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)
Run Code Online (Sandbox Code Playgroud)

实际上,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>
Run Code Online (Sandbox Code Playgroud)

(我从文档中找到上述引用的方式>>> help(m)相当于在线文档).


hpa*_*ulj 9

为了扩展将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
Run Code Online (Sandbox Code Playgroud)

显然,选择单个元素,dok是紧固(计算转换时间).这种格式实际上是一个字典,当然它具有快速的元素访问权限.

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

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