Scipy中常見的幾類矩陣,包括lil_matrix和csc_matrix、coo_matrix,最近在研究網絡結構的表示學習,需要使用這些工具。
官方文檔其實已經講得比較詳細了,我這里再補充一點,把問題講得更加簡單明白。
csc_matrix:
Example
>>> import numpy as np
>>> from scipy.sparse import csc_matrix
>>> csc_matrix((3, 4), dtype=np.int8).toarray()
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)
>>>
>>> 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]])
data是存儲的數據,矩陣以列來存儲,很多人學習完了線性代數,甚至不知道矩陣一般是以列還是以行來存儲。從向量Vector的角度來看,矩陣都應該以列方式來存儲,以列來理解和存儲更符合實際需要,我們常用的x = [1,2,3,5],在運算時都要進行一個轉置x^T。實際上Numpy中矩陣也是使用csc_matrix存儲。
row, col data這里的意思就顯而易見了, row[i], col[i]存儲的數據為data[i], 0行,0列 存儲了1; 2行,0列存儲了2; 2行,2列存儲了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])
>>> csc_matrix((data, indices, indptr), shape=(3, 3)).toarray()
array([[1, 0, 4],
[0, 0, 5],
[2, 3, 6]])
這個略微復雜,但其實也非常容易理解: indptr表示的是indices矩陣里的開始和結尾的index, indptr [0, 2]表示indices[0:2]存儲了第一列的數據所位置0行和2行,indices[2:3]存儲了第二列的數據位置,即2,第2行(注意從0行開始), 每個indices[i]對應一個data[i]。注意Python list[0:i]取值為list[0....i-1]實際上indeces[0:2]只取了indices第一個和第二個數值0和2,代表數據在0和2行,其余位置皆為0;inices[2:3]取了indices[2]的數值2,代表數據在第2行,其余位置皆為0.
coo_matrix
這個就更容易了,給我一分鐘。直接上例子如下:即n行,m列存了data[i],其余位置皆為0.
>>> from scipy.sparse import coo_matrix
>>> coo_matrix((3, 4), dtype=np.int8).toarray()
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)
>>>
>>> row = np.array([0, 3, 1, 0])
>>> col = np.array([0, 3, 1, 2])
>>> data = np.array([4, 5, 7, 9])
>>> coo_matrix((data, (row, col)), shape=(4, 4)).toarray()
array([[4, 0, 9, 0],
[0, 7, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 5]])
轉自csdn
參考文檔
https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csc_matrix.html#scipy.sparse.csc_matrix
https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.html#scipy.sparse.coo_matrix