1. 程式人生 > >scipy.sparse中csc_martrix和csr_matrix兩個稀疏矩陣的區別

scipy.sparse中csc_martrix和csr_matrix兩個稀疏矩陣的區別

官方參考文件連結:

https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csc_matrix.html

https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html

直接上官方文件的例子進行解釋:

第一種情況:csc_matrix((data, (row, col)), shape=(3, 3))和csr_matrix((data,(row,col)),shape=(3,3))
>>> row = np.array([
0, 2, 2, 0, 1, 2]) >>> col = np.array([0, 0, 1, 2, 2, 2]) >>> data = np.array([1, 2, 3, 4, 5, 6]) >>> csc_matrix((data, (row, col)), shape=(3, 3)).toarray() array([[1, 0, 4], [0, 0, 5], [2, 3, 6]])
>>> row = np.array([0, 0, 1, 2, 2, 2])
>>> col = np.
array([0, 2, 2, 0, 1, 2]) >>> data = np.array([1, 2, 3, 4, 5, 6]) >>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray() array([[1, 0, 2], [0, 0, 3], [4, 5, 6]])
可以看出第一種情況下,由於行和列的index均為壓縮,兩者沒有任何區別。

其中,row=np.array([0,0,1,2,2,2])代表data中六個元素在矩陣中的行索引值,

col=np.array([0,2,2,

0,1,2])代表data中六個元素在矩陣中的行索引值。

csr_matrix為例,data中的 元素‘3’ 的行索引為1,列索引為2,表示 ‘3’ 在稀疏矩陣的第1行第2列(矩陣的行列以0開始);

		同樣,data中的元素 ‘4’ 的行索引為2,列索引為0,表示 ‘4’ 在稀疏矩陣的第2行第0列(矩陣的行列以0開始);
其餘的不在索引中的3×3階(shape(3,3)可知矩陣為3×3階)矩陣中的元素以0填充。
第二種情況:csc_matrix((data,indices,indptr),shape=(3,3)) c sr_matrix((data,indices,indptr),shape=(3,3))
>>> indptr = np.array([0, 2, 3, 6])
>>> indices = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> csc_matrix((data, indices, indptr), shape=(3, 3)).toarray()
array([[1, 0, 4],
       [0, 0, 5],
       [2, 3, 6]])
>>> indptr = np.array([0, 2, 3, 6])
>>> indices = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> csr_matrix((data, indices, indptr), shape=(3, 3)).toarray()
array([[1, 0, 2],
       [0, 0, 3],
       [4, 5, 6]])
第二種情況下,csc_matrix(Compressed Sparse Column matrix)表示對列<索引>進行了壓縮,行索引並未壓縮。indices表示的是未壓縮的行索引,indptr表示的是壓縮後的列索引。csr_matrix(Compressed Sparse Column matrix)表示對行<索引>進行了壓縮,列索引並未壓縮。indices表示的是未壓縮的列索引,indptr表示的是壓縮後的行索引。
這樣,以csc_matrix為例:
data中的1,2,3,4,5,6六個元素對應的行分別為0,2,2,0,1,2行。即元素1和4位於矩陣的第0行;元素2,3,6位於矩陣的第2行;元素5位於矩陣的第1行。再看
indptr中的元素;首先看第一個為0,表示data中的第一個元素1位於第0列。由於前面已經確定了行,所以,data中的元素1有了確定的位置(第0行,第0列)。indptr中的第二個元素為2,減去前邊的第一個元素0,即2-0=2,表示data中的前兩個元素(1,2)位於第0(indptr中元素0的索引值)列,這樣data中元素1,2的位置也確定了,分別位於(第0行第0列和第2行第0列);同樣3-2=1,表示data中第三個元素位於第1(indptr中元素2的索引值)列;6-3=3表示元素4,5,6三個元素位於位於第2(indptr中元素3的索引值)列。加上前邊確定的行,可以確定這幾個元素的位置。其他位置填充0.