csc_matrix

许多同学可能在使用Python进行科学计算时用过稀疏矩阵的构造,而python的科学计算包scipy.sparse是很好的一个解决稀疏矩阵构造/计算的包。
下面我介绍一下scipy.sparse包中csc/csr矩阵的构造中一个比较难理解的构造方法:
官方文档(http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csc_matrix.html)中对csc矩阵的构造方法中最后一种:
csc_matrix((data, indices, indptr), [shape=(M, N)])
is the standard CSC representation where the row indices for column i are stored in indices[indptr[i]:indptr[i+1]] and their corresponding values are stored in data[indptr[i]:indptr[i+1]]. If the shape parameter is not supplied, the matrix dimensions are inferred from the index arrays.这个构造方法比较难理解,这里的indptr indices分别是什么呢?
对于以下代码来说:
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()
indices代表了非零元素的行信息,它与indptr共同定位元素的行和列
首先对于0列来说 indptr[0]:indptr[1]=[0,1] 再看行indices[0,1]=[0,2] 数据data[0,1]=[1,2] 说明列0在行0和2上有数据1和2
对于1列来说 indptr[1]:indptr[2]=[2] 行indices[2]=[2] 数据data[2]=[3] 说明列2在行2上有数据3
对于2列来说 indptr[2]:indptr[3]=[3,4,5] 行indices[3,4,5]=[0,1,2] 数据data[3,4,5]=[4,5,6]
所以上述代码可以得到矩阵:
array([[1, 0, 4],
[0, 0, 5],
[2, 3, 6]])

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容