十分钟理解Scipy.csc_matrix和coo_matrix

来源:互联网 发布:ubuntu redis 安装 编辑:程序博客网 时间:2024/06/06 03:33

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]])


参考文档

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

0 0
原创粉丝点击