| 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>
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
从coo矩阵文档:
实际上,
csr_matrix
以预期的方式支持索引:(我从文档中找到上述引用的方式是
>>> help(m)
,相当于the online docs)。为了扩展将
coo
矩阵转换为csr
索引的过程,下面是一些小型稀疏矩阵的计时制作矩阵
显然,对于选择单个元素来说,
dok
是最快的(计算转换时间)。这种格式实际上是一个字典,当然可以快速访问元素。但是,如果您经常访问整行或整列,或者在行或列上迭代,则需要更仔细地阅读文档,并且可能需要对典型的数组进行自己的时间测试。
如果您正在设置值,而不仅仅是读取它们,则计时甚至实现可能会有所不同。如果尝试更改
csr
或csc
格式的0
元素,则会收到效率警告。相关问题 更多 >
编程相关推荐