這是一個非常簡單的問題。對於像coo_matrix這樣的SciPy稀疏矩陣,如何訪問單個元素?訪問coo_matrix中的元素
給出Eigen線性代數庫的一個類比。
myMatrix.coeffRef(i,j)
這是一個非常簡單的問題。對於像coo_matrix這樣的SciPy稀疏矩陣,如何訪問單個元素?訪問coo_matrix中的元素
給出Eigen線性代數庫的一個類比。
myMatrix.coeffRef(i,j)
從文檔的coo_matrix:人們可以使用coeffRef如下訪問元素(I,J)
| 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)。
謝謝。這將工作。 – haripkannan
'todok'可能會更快。 – hpaulj
爲了擴展一個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
,是fastests (計算轉換時間)。這種格式實際上是一個字典,當然有快速的元素訪問。
但是,如果您經常訪問整行或整列或迭代行或列,則需要更仔細地閱讀文檔,並可能對自己的典型陣列進行時間測試。
如果您正在設置值,而不僅僅是讀取它們,時間點甚至實施可能會有所不同。如果您嘗試更改csr
或csc
格式的0
元素,則會收到效率警告。
非常感謝。非常有用的信息。 – haripkannan
'mymatrix [i,j]' – Jaime
我試過了。我得到以下錯誤:TypeError:'coo_matrix'對象沒有屬性'__getitem__' – haripkannan
看看其他稀疏格式 – hpaulj