• scipy.sparse
  • scipy.sparse的稀疏矩阵类型
  • scipy.sparse中的矩阵函数
    • 构造函数
    • 判别函数
    • 其他有用函数
  • scipy.sparse中的作用在矩阵的内函数
    • 针对元素的函数
    • 转化函数
    • 其他函数

从下面的Scipy官网对Scipy的描述可以发现:其实SciPy是基于python的用于数学、科学以及工程计算的开源生态系统。数据分析常用的numpy,pandas,matplotlib包都包含在这里面,scipy包自然也就包含在里面了。

SciPy (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering. In particular, these are some of the core packages:Numpy, SciPy library, Matplotlib, IPython, Sympy and Pandas.
——[SciPy.org]

Scipy官网还对scipy包进行了简单的介绍。

Scipy library : Fundamental library for scientific computing
The SciPy library is one of the core packages that make up the SciPy stack. It provides many user-friendly and efficient numerical routines such as routines for numerical integration and optimization.

scipy.sparse

scipy包下包含许多数学计算优化的函数,最近由于接触到向量化的python操作,发现sklearn.feature_extraction.text.CountVectorizer函数在调用fit_transform()后得到的数据格式是sparse matrix (稀疏矩阵) 格式的,再经过资料查找知道这个数据类型是属于scipy.sparse,对应形式如下。

<178444x1838 sparse matrix of type '<class 'numpy.int64'>'with 10950 stored elements in Compressed Sparse Row format>

很多资料都有稀疏矩阵的定义,以下截取自百度百科。

在矩阵中,若数值为0的元素数目远远多于非0元素的数目,并且非0元素分布没有规律时,则称该矩阵为稀疏矩阵。
——[百度百科]

进一步,在scipy.sparse的官方介绍网站下定义了以下七种稀疏矩阵以及基矩阵,还有稀疏矩阵的各种函数。

scipy.sparse的稀疏矩阵类型

  • bsr_matrix(arg1[, shape, dtype, copy, blocksize])
    Block Sparse Row matrix
>>> '''
BSR矩阵中的inptr列表的第i个元素与i+1个元素是储存第i行的数据的列索引以及数据的区间索引,即indices[indptr[i]:indptr[i+1]]为第i行元素的列索引,data[indptr[i]: indptr[i+1]]为第i行元素的data。
在下面的例子中,对于第0行,indptr[0]:indptr[1] -> 0:2, 因此第0行的列为indice[0:2]=[0,2],data为data[0:2]=array([[[1, 1],[1, 1]],[[2, 2],[2, 2]]]),对应的就是最后结果的第0,1行。
'''
>>> 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]).repeat(4).reshape(6, 2, 2)
>>> bsr_matrix((data,indices,indptr), shape=(6, 6)).toarray()
array([[1, 1, 0, 0, 2, 2],[1, 1, 0, 0, 2, 2],[0, 0, 0, 0, 3, 3],[0, 0, 0, 0, 3, 3],[4, 4, 5, 5, 6, 6],[4, 4, 5, 5, 6, 6]])
  • coo_matrix(arg1[, shape, dtype, copy])
    A sparse matrix in COOrdinate format:
>>> '''
不难发现,coo_matrix是可以根据行和列索引进行data值的累加。
'''
>>> row  = np.array([0, 0, 1, 3, 1, 0, 0])
>>> col  = np.array([0, 2, 1, 3, 1, 0, 0])
>>> data = np.array([1, 1, 1, 1, 1, 1, 1])
>>> coo_matrix((data, (row, col)), shape=(4, 4)).toarray()
array([[3, 0, 1, 0],[0, 2, 0, 0],[0, 0, 0, 0],[0, 0, 0, 1]])
  • csc_matrix(arg1[, shape, dtype, copy])
    Compressed Sparse Column matrix
    csc_matrix的初始化方法可以是bsr_matrix的初始化方法,也可以是coo_matrix的初始化方法,该csc_matrix与下面的csr_matrix是比较常用的稀疏矩阵。

  • csr_matrix(arg1[, shape, dtype, copy])
    Compressed Sparse Row matrix
    csr_matrix的初始化与csc_matrix一致。

  • dia_matrix(arg1[, shape, dtype, copy])
    Sparse matrix with DIAgonal storage

>>> #data定义对角线元素,在这里是[1,2,3,4]。
>>> data = np.array([[1, 2, 3, 4]]).repeat(3, axis=0)
>>> #offsets定义对角线的偏移量,0代表正对角线,正数代表往上偏移,负数代表往下偏移
>>> offsets = np.array([0, -1, 2])
>>> dia_matrix((data, offsets), shape=(4, 4)).toarray()
array([[1, 0, 3, 0],[1, 2, 0, 4],[0, 2, 3, 0],[0, 0, 3, 4]])
  • dok_matrix(arg1[, shape, dtype, copy])
    Dictionary Of Keys based sparse matrix
    dok_matrix可以高效地逐渐构造稀疏矩阵。
>>> S = dok_matrix((5, 5), dtype=np.float32)
>>> for i in range(5):
...     for j in range(5):
...         S[i, j] = i + j
>>> S.toarray()
array([[0., 1., 2., 3., 4.],[1., 2., 3., 4., 5.],[2., 3., 4., 5., 6.],[3., 4., 5., 6., 7.],[4., 5., 6., 7., 8.]], dtype=float32)
  • lil_matrix(arg1[, shape, dtype, copy])
    Row-based linked list sparse matrix
    与dok_matrix类似,也是可以高效地插入元素更新矩阵。

  • spmatrixSparse([maxprint])
    上面所有稀疏矩阵类型的基类型,不能被实例化

注意除最后一个基矩阵以外,其他七种稀疏矩阵都可以用以下方式(1、指定行索引、列索引以及对应的数据;2、指定array;3、稀疏矩阵之间的转化)来初始化,我们稀疏矩阵类型函数模板化为sparse_matrix

>>> #行索引
>>> row  = np.array([0, 3, 1, 0])
>>> #列索引
>>> col  = np.array([0, 3, 1, 2])
>>> #具体数据
>>> data = np.array([4, 5, 7, 9])
>>> #第一种方式
>>> sparse_matrix((data, (row, col)), shape=(4, 4)).toarray()
array([[4, 0, 9, 0],[0, 7, 0, 0],[0, 0, 0, 0],[0, 0, 0, 5]])
>>> #第二种方式(array可以是list,也可以是np.array)
>>> sparse_matrix(array).toarray()
>>> #第三种方式(sparse_matrix_other为其他稀疏矩阵类型,等价于sparse_matrix_other.tosparse(),具体的内函数形式根据需要转化的sparse_matrix类型而定)
>>> sparse_matrix(sparse_matrix_other).toarray()

scipy.sparse中的矩阵函数

下面我只列出比较有用的函数,其他的函数可以参见scipy.sparse官网。

构造函数

  • eye(m[, n, k, dtype, format]):对角线为1的稀疏矩阵
  • identity(n[, dtype, format]):单位矩阵
  • diags(diagonals[, offsets, shape, format, dtype]):构造对角矩阵(含偏移量)
  • spdiags(data, diags, m, n[, format]):从矩阵中返回含偏移量的对角稀疏矩阵
  • hstack(blocks[, format, dtype]) Stack sparse matrices horizontally (column wise)
  • vstack(blocks[, format, dtype]) Stack sparse matrices vertically (row wise)

判别函数

  • issparse(x):x是否为sparse类型
  • isspmatrix(x):x是否为sparse类型
  • isspmatrix_csc(x):x是否为csc_matrix类型
  • isspmatrix_csr(x):x是否为csr_matrix类型
  • isspmatrix_bsr(x):x是否为bsr_matrix类型
  • isspmatrix_lil(x):x是否为lil_matrix类型
  • isspmatrix_dok(x):x是否为dok_matrix类型
  • isspmatrix_coo(x):x是否为coo_matrix类型
  • isspmatrix_dia(x):x是否为dia_matrix类型

其他有用函数

  • save_npz(file, matrix[, compressed]):以.npz格式保存稀疏矩阵
  • load_npz(file):导入.npz格式的稀疏矩阵
  • find(A):返回稀疏矩阵A中的非零元的位置以及数值

scipy.sparse中的作用在矩阵的内函数

下面的函数只针对csr_matrix列出,其他稀疏矩阵格式的函数也类似,具体可以查看对应稀疏矩阵的说明文档下面的函数说明部分。

针对元素的函数

内函数中有很多作用在矩阵元素的函数,下面列出一些函数。
- arcsin():每个元素进行arcsin运算
- floor():每个元素进行floor运算
- sqrt():每个元素进行sqrt运算
- maximum(other):比较稀疏矩阵与other矩阵的每个元素,返回最大值

转化函数

  • todense([order, out]):返回稀疏矩阵的np.matrix形式
  • toarray([order, out]):返回稀疏矩阵的np.array形式
  • tobsr([blocksize, copy]):返回稀疏矩阵的bsr_matrix形式
  • tocoo([copy]):返回稀疏矩阵的coo_matrix形式
  • tocsc([copy]):返回稀疏矩阵的csc_matrix形式
  • tocsr([copy]):返回稀疏矩阵的csr_matrix形式
  • todia([copy]):返回稀疏矩阵的dia_matrix形式
  • todok([copy]):返回稀疏矩阵的dok_matrix形式
  • tolil([copy]):返回稀疏矩阵的lil_matrix形式

其他函数

  • get_shape():返回稀疏矩阵的维度
  • max([axis, out]):返回稀疏矩阵沿着某个轴的最大值
  • reshape(self, shape[, order, copy]):将稀疏矩阵的维度重构
  • diagonal([k]):返回第k个对角元素,但是在我的python3版本中k不起作用。
  • dot(other):与other矩阵的矩阵乘法

scipy.sparse的一些整理相关推荐

  1. Python中scipy.sparse的一些整理

    scipy.sparse scipy.sparse的稀疏矩阵类型 scipy.sparse中的矩阵函数 构造函数 判别函数 其他有用函数 scipy.sparse中的作用在矩阵的内函数 针对元素的函数 ...

  2. scipy.sparse.coo_matrix、csr_matrix、lil_matrix、dia_matrix

    文章目录 coo_matrix csr_matrix lil_matrix dia_matrix coo_matrix 1.coo啥意思?COOrdinate(坐标) 2.那么coo_matrix又是 ...

  3. scipy笔记:scipy.sparse

    1 稀疏矩阵介绍 在networkx包中,很多运算返回的是sparse matrix(如nx.laplacian_matrix),这是稀疏矩阵格式.隶属于scipy.sparse import net ...

  4. scipy.sparse.csr_matrix函数和coo_matrix函数

    Scipy高级科学计算库:和Numpy联系很密切,Scipy一般都是操控Numpy数组来进行科学计算.统计分析,所以可以说是基于Numpy之上了.Scipy有很多子模块可以应对不同的应用,例如插值运算 ...

  5. 关于稀疏矩阵转化为稠密矩阵问题 (scipy.sparse格式和tensor稀疏张量格式)

    scipy.sparse: todense() pytorch中的稀疏张量tensor: to_dense()

  6. python 的csr_Python scipy.sparse.csr_matrix()[csc_matrix()]

    csr_matrix是Compressed Sparse Row matrix的缩写组合,下面介绍其两种初始化方法 csr_matrix((data, (row_ind, col_ind)), [sh ...

  7. scipy.sparse、pandas.sparse、sklearn稀疏矩阵的使用

    单机环境下,如果特征较为稀疏且矩阵较大,那么就会出现内存问题,如果不上分布式 + 不用Mars/Dask/CuPy等工具,那么稀疏矩阵就是一条比较容易实现的路. 文章目录 1 scipy.sparse ...

  8. scipy.sparse求稀疏矩阵前k个特征值

    背景: 要在python中处理7000*7000的稀疏矩阵,计算前k小的特征值和相应的特征向量.不想在matlab中做这件事了,所有的数据预处理和展现工作都想在python中完成.然而一般的linal ...

  9. scipy.sparse.vstack

    参考  https://cloud.tencent.com/developer/article/1525041 scipy.sparse.vstack(blocks, format=None, dty ...

最新文章

  1. 首个获得FDA批准的脑机接口设备:“突破性”脑机接口设备用于造福人类
  2. mysql+多列外键_MySQL中的多列外键?
  3. Application Transport Security has blocked a clear
  4. 数据结构 2-3-4 静态链表
  5. Oracle网格控制器OMA端安装Yast
  6. 数据可视化上集:使用Gliffy,ProcessOn迅速绘制论文中的流程图,系统结构图
  7. 数组分割 java_分割java数组
  8. P3966 [TJOI2013]单词(AC自动机)
  9. 8.认识robots.txt到爬取信息
  10. 让技术Leader疯狂点赞的Linux速成手册,到底有多强悍?
  11. 史莱姆区块查找 超简单java代码
  12. MySQL创建用户并授权、删除用户(密码规则)
  13. 刹车离合同时踩非常危险
  14. 智能机房动力环境集中监控管理系统
  15. “视而不见”—有关不注意视盲现象的研究
  16. 无法远程访问工作组计算机,如何在另一个工作组计算机上进行远程调试?
  17. ELYFI爱立丰举办“2021中国NFT与餐饮新思路高峰论坛” 圆满成功
  18. php在线支付之支付宝
  19. 2-6 行为面试常见问题与回答技巧
  20. 中国冷兵器时代的十大勇将

热门文章

  1. 第三方插件的引用(4):JAVA网站接入QQ登录
  2. Android 启用/禁用蓝牙传输文件功能(不能影响蓝牙耳机听歌)
  3. 【经典蓝牙】蓝牙 A2DP协议分析
  4. 数字电路_2. 各类触发器
  5. Kafka 控制器的作用(Controller)
  6. iA Writer for Mac(mac好用的写作软件)
  7. FME会员期刊(2012秋季版)——更新完毕
  8. 怎么快速发表期刊论文
  9. 找素数,分解质因数(python)
  10. package.json 中的波浪号(~)和插入符号(^)有什么区别?