您的位置:首页 > 其它

scipy.sparse中csc_martrix和csr_matrix两个稀疏矩阵的区别

2017-11-28 16:52 621 查看
官方参考文档链接: 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.

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  csc_matrix csr_matrix