工程實踐中,多數情況下,大矩陣一般都為稀疏矩陣,所以如何處理稀疏矩陣在實際中就非常重要。本文以Python里中的實現為例,首先來探討一下稀疏矩陣是如何存儲表示的。
1.sparse模塊初探
python中scipy模塊中,有一個模塊叫sparse模塊,就是專門為了解決稀疏矩陣而生。本文的大部分內容,其實就是基于sparse模塊而來的。 
第一步自然就是導入sparse模塊
>>> from scipy import sparse
然后help一把,先來看個大概
>>> help(sparse)
直接找到我們最關心的部分:
Usage information ================= There are seven available sparse matrix types: 1. csc_matrix: Compressed Sparse Column format 2. csr_matrix: Compressed Sparse Row format 3. bsr_matrix: Block Sparse Row format 4. lil_matrix: List of Lists format 5. dok_matrix: Dictionary of Keys format 6. coo_matrix: COOrdinate format (aka IJV, triplet format) 7. dia_matrix: DIAgonal format To construct a matrix efficiently, use either dok_matrix or lil_matrix. The lil_matrix class supports basic slicing and fancy indexing with a similar syntax to NumPy arrays. As illustrated below, the COO format may also be used to efficiently construct matrices. To perform manipulations such as multiplication or inversion, first convert the matrix to either CSC or CSR format. The lil_matrix format is row-based, so conversion to CSR is efficient, whereas conversion to CSC is less so. All conversions among the CSR, CSC, and COO formats are efficient, linear-time operations.
通過這段描述,我們對sparse模塊就有了個大致的了解。sparse模塊里面有7種存儲稀疏矩陣的方式。接下來,我們對這7種方式來做個一一介紹。
2.coo_matrix
coo_matrix是最簡單的存儲方式。采用三個數組row、col和data保存非零元素的信息。這三個數組的長度相同,row保存元素的行,col保存元素的列,data保存元素的值。一般來說,coo_matrix主要用來創建矩陣,因為coo_matrix無法對矩陣的元素進行增刪改等操作,一旦矩陣創建成功以后,會轉化為其他形式的矩陣。
>>> row = [2,2,3,2]>>> col = [3,4,2,3]>>> c = sparse.coo_matrix((data,(row,col)),shape=(5,6))>>> print c.toarray()[[0 0 0 0 0 0] [0 0 0 0 0 0] [0 0 0 5 2 0] [0 0 3 0 0 0] [0 0 0 0 0 0]]
稍微需要注意的一點是,用coo_matrix創建矩陣的時候,相同的行列坐標可以出現多次。矩陣被真正創建完成以后,相應的坐標值會加起來得到最終的結果。
3.dok_matrix與lil_matrix
dok_matrix和lil_matrix適用的場景是逐漸添加矩陣的元素。doc_matrix的策略是采用字典來記錄矩陣中不為0的元素。自然,字典的key存的是記錄元素的位置信息的元祖,value是記錄元素的具體值。
新聞熱點
疑難解答