Scipy 基础 —— 稀疏矩阵

来源:互联网 发布:网上编程教育 编辑:程序博客网 时间:2024/06/06 02:39

稀疏矩阵,也即仅存储非零元素,既提升了矩阵操作的效率,也节省了内存。

稀疏矩阵的存储格式(Sparse Matrix Storage Formats)

很多语言、平台都支持稀疏矩阵这一数据存储结构,尽管语言、平台各异,但是多数采用相同的基本技术,即存储矩阵所有的非零元素到一个线性数组中,并提供辅助数组来描述原数组中非零元素的位置

以下是几种常见的稀疏矩阵存储格式:

  • (1)Coordinate Format (COO)


    这里写图片描述

Scipy 支持

不同的存储形式在sparse模块中对应如下:

bsr_matrix(arg1[, shape, dtype, copy, blocksize]) Block Sparse Row matrixcoo_matrix(arg1[, shape, dtype, copy]) A sparse matrix in COOrdinate format.csc_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Column matrixcsr_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Row matrixdia_matrix(arg1[, shape, dtype, copy]) Sparse matrix with DIAgonal storagedok_matrix(arg1[, shape, dtype, copy]) Dictionary Of Keys based sparse matrix.lil_matrix(arg1[, shape, dtype, copy]) Row-based linked list sparse matrix

构建一个 COO format 的稀疏矩阵:

>>>>>> from scipy import sparse>>> from numpy import array>>> I = array([0,3,1,0])>>> J = array([0,3,1,2])>>> V = array([4,5,7,9])>>> A = sparse.coo_matrix((V,(I,J)),shape=(4,4))>>> A.todense()matrix([[4, 0, 9, 0],        [0, 7, 0, 0],        [0, 0, 0, 0],        [0, 0, 0, 5]])

sparse ⇒ dense

todense()方法实现稀疏向密集型的转换;

references

[1] Python SciPy Sparse模块学习笔记

[2] Sparse matrices (scipy.sparse)

[3] 稀疏矩阵的存储格式(Sparse Matrix Storage Formats)

0 0
原创粉丝点击