首页 > 编程 > Python > 正文

python实现稀疏矩阵示例代码

2020-02-16 01:40:54
字体:
来源:转载
供稿:网友

工程实践中,多数情况下,大矩阵一般都为稀疏矩阵,所以如何处理稀疏矩阵在实际中就非常重要。本文以Python里中的实现为例,首先来探讨一下稀疏矩阵是如何存储表示的。

1.sparse模块初探

python中scipy模块中,有一个模块叫sparse模块,就是专门为了解决稀疏矩阵而生。本文的大部分内容,其实就是基于sparse模块而来的。

第一步自然就是导入sparse模块

>>> from scipy import sparse

然后help一把,先来看个大概

>>> help(sparse)

直接找到我们最关心的部分:

  Usage information  =================  There are seven available sparse matrix types:    1. csc_matrix: Compressed Sparse Column format    2. csr_matrix: Compressed Sparse Row format    3. bsr_matrix: Block Sparse Row format    4. lil_matrix: List of Lists format    5. dok_matrix: Dictionary of Keys format    6. coo_matrix: COOrdinate format (aka IJV, triplet format)    7. dia_matrix: DIAgonal format  To construct a matrix efficiently, use either dok_matrix or lil_matrix.  The lil_matrix class supports basic slicing and fancy  indexing with a similar syntax to NumPy arrays. As illustrated below,  the COO format may also be used to efficiently construct matrices.  To perform manipulations such as multiplication or inversion, first  convert the matrix to either CSC or CSR format. The lil_matrix format is  row-based, so conversion to CSR is efficient, whereas conversion to CSC  is less so.  All conversions among the CSR, CSC, and COO formats are efficient,  linear-time operations.

通过这段描述,我们对sparse模块就有了个大致的了解。sparse模块里面有7种存储稀疏矩阵的方式。接下来,我们对这7种方式来做个一一介绍。

2.coo_matrix

coo_matrix是最简单的存储方式。采用三个数组row、col和data保存非零元素的信息。这三个数组的长度相同,row保存元素的行,col保存元素的列,data保存元素的值。一般来说,coo_matrix主要用来创建矩阵,因为coo_matrix无法对矩阵的元素进行增删改等操作,一旦矩阵创建成功以后,会转化为其他形式的矩阵。

>>> row = [2,2,3,2]>>> col = [3,4,2,3]>>> c = sparse.coo_matrix((data,(row,col)),shape=(5,6))>>> print c.toarray()[[0 0 0 0 0 0] [0 0 0 0 0 0] [0 0 0 5 2 0] [0 0 3 0 0 0] [0 0 0 0 0 0]]

稍微需要注意的一点是,用coo_matrix创建矩阵的时候,相同的行列坐标可以出现多次。矩阵被真正创建完成以后,相应的坐标值会加起来得到最终的结果。

3.dok_matrix与lil_matrix

dok_matrix和lil_matrix适用的场景是逐渐添加矩阵的元素。doc_matrix的策略是采用字典来记录矩阵中不为0的元素。自然,字典的key存的是记录元素的位置信息的元祖,value是记录元素的具体值。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表