• 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矩阵的矩阵乘法

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

  1. python中Scipy模块求取积分

    python中Scipy模块求取积分的方法: SciPy下实现求函数的积分的函数的基本使用,积分,高等数学里有大量的讲述,基本意思就是求曲线下面积之和. 其中rn可认为是偏差,一般可以忽略不计,wi可 ...

  2. python中scipy及pandas安装成功,但import时出错,教你解决问题

    1.python中scipy 安装成功,但import时出错,即出现如下问题 按照流程,先安装numpy+mkl,再安装scipy,cmd命令窗口提示成功安装,但是import时却错误,这个问题我研究 ...

  3. scipy.sparse的一些整理

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

  4. Python中scipy库中csr_matrix()函数和csc_matrix()函数的解释

    在使用Python进行科学计算时经常需要用到稀疏矩阵的构造,而python的科学计算包scipy.sparse是很好的一个解决稀疏矩阵构造/计算的包. 构造稀疏矩阵常用的两个函数为:csr_matri ...

  5. Python中scipy库对mat文件进行读写操作

    mat文件是以字典的格式进行存储的,有时候Python中需要对字典进行读写,使用Python处理matlab的mat文件时,可以使用scipy库中的函数进行操作. 导入scipy库 对mat文件的读写 ...

  6. Python中最全魔术方法整理

    Python中的魔术方法 所谓魔法函数(Magic Methods),是Python的一种高级语法,允许你在类中自定义函数,并绑定到类的特殊方法中.比如在类A中自定义__str__()函数,则在调用s ...

  7. python中常见关键字英文含义整理

    文章版: 序号 英文 含义 用法 1 Python 蟒蛇 2 code 代码 3 turtle 海龟 海龟库 4 from...import... 从...导入库 from Codemao impor ...

  8. Python中scipy中weibull分布的计算

    scipy.stats.exponweib:scipy包中计算weibull分布的函数. from scipy.stats import exponweib 密度函数的格式:exponweib.pdf ...

  9. python中scipy.optimize_浅谈SciPy中的optimize.minimize实现受限优化问题

    问题描述:有一批样本x,每个样本都有几个固定的标签,如(男,24岁,上海),需要从中抽取一批样本,使样本总的标签比例满足分布P(x),如(男:女=49%:51%.20岁:30岁=9%:11%..... ...

最新文章

  1. 看漫画学python电子书-看漫画还能学Python❓❓❓| 0基础小白福音
  2. Windows环境下Pin(二进制动态插桩引擎)搭建
  3. jQuery的链Chaining
  4. ES6_对象简洁语法_note
  5. 音视频开发(5)---FFMPEG视音频编解码零基础学习方法
  6. 使用base标签后图片无法加载_Spring 源码学习(二)-默认标签解析
  7. gitlab创建分支上传文件_代码管理-gitlab使用方法建议
  8. TabLayout实现自定义标题栏目功能
  9. JOHNSON算法:流水作业最优调度问题
  10. 2020数据分析人才及CDA持证人行业报告
  11. ecshop二次开发之模板整合
  12. python能做什么工作好-python可以做什么工作
  13. Kaggle 入门 Crime
  14. P1129 [ZJOI2007]矩阵游戏 (匈牙利算法)
  15. 解决99%的卡刷包无法通过ROM制作工具修改的问题
  16. Philosopher’s Walk ICPC 2017 Daejeon F dfs 分治
  17. OpenMV学习(0):环境搭配
  18. 关于新光源建设的一些想法
  19. POCO C++ 在IOS上的使用
  20. 【云原生】企业级容器管理平台Openshift介绍

热门文章

  1. 科研笔记-无线感知第1篇(基于WIFI CSI进行人体行为识别调查)
  2. 帝国CMS 手机版制作+帝国PC跳转到手机+重新定向
  3. 游戏蓝牙耳机哪个品牌好?打游戏专用的蓝牙耳机推荐
  4. 【2019.5.31】学习·分享会·总结???
  5. 港大禁用 ChatGPT 等 AI 工具,网友:“从万众瞩目到千夫所指?”
  6. python制作个人网页_熬了一夜!我用Python做了一个网站,帮小姐姐生成漫画头像...
  7. 损失函数定义及常用损失函数
  8. MIME之quoted-printable编码与base64编码(例题+图解)
  9. 计算机键盘保护膜的生产工艺流程,电脑键盘用水转印键帽的制作方法
  10. 英语中‘s的几种用法