稀疏矩阵,也即仅存储非零元素,既提升了矩阵操作的效率,也节省了内存。
稀疏矩阵的存储格式(Sparse Matrix Storage Formats)
很多语言、平台都支持稀疏矩阵这一数据存储结构,尽管语言、平台各异,但是多数采用相同的基本技术,即存储矩阵所有的非零元素到一个线性数组中,并提供辅助数组来描述原数组中非零元素的位置。
以下是几种常见的稀疏矩阵存储格式:
(1)Coordinate Format (COO)
Scipy 支持
不同的存储形式在sparse模块中对应如下:
bsr_matrix(arg1[, shape, dtype, copy, blocksize]) Block Sparse Row matrix
coo_matrix(arg1[, shape, dtype, copy]) A sparse matrix in COOrdinate format.
csc_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Column matrix
csr_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Row matrix
dia_matrix(arg1[, shape, dtype, copy]) Sparse matrix with DIAgonal storage
dok_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()方法实现稀疏向密集型的转换;