python 画风场 scipy_Python数据分析及可视化实例之Scipy

# coding: utf-8

# # 稀疏矩阵

# `Scipy` 提供了稀疏矩阵的支持(`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 格式在构建矩阵时比较高效

# - CSC 和 CSR 格式在乘法计算时比较高效

# ## 构建稀疏矩阵

# In[1]:

from scipy.sparse import *

import numpy as np

# 创建一个空的稀疏矩阵:

# In[2]:

coo_matrix((2,3))

# 也可以使用一个已有的矩阵或数组或列表中创建新矩阵:

# In[4]:

A = coo_matrix([[1,2,0],[0,0,3],[4,0,5]])

print(A)

# 不同格式的稀疏矩阵可以相互转化:

# In[5]:

type(A)

# In[6]:

B = A.tocsr()

type(B)

# 可以转化为普通矩阵:

# In[7]:

C = A.todense()

C

# 与向量的乘法:

# In[8]:

v = np.array([1,0,-1])

A.dot(v)

# 还可以传入一个 `(data, (row, col))` 的元组来构建稀疏矩阵:

# In[9]:

I = np.array([0,3,1,0])

J = np.array([0,3,1,2])

V = np.array([4,5,7,9])

A = coo_matrix((V,(I,J)),shape=(4,4))

# In[11]:

print(A)

# COO 格式的稀疏矩阵在构建的时候只是简单的将坐标和值加到后面,对于重复的坐标不进行处理:

# In[13]:

I = np.array([0,0,1,3,1,0,0])

J = np.array([0,2,1,3,1,0,0])

V = np.array([1,1,1,1,1,1,1])

B = coo_matrix((V,(I,J)),shape=(4,4))

print(B)

# 转换成 CSR 格式会自动将相同坐标的值合并:

# In[15]:

C = B.tocsr()

print(C)

# ## 求解微分方程

# In[16]:

from scipy.sparse import lil_matrix

from scipy.sparse.linalg import spsolve

from numpy.linalg import solve, norm

from numpy.random import rand

# 构建 `1000 x 1000` 的稀疏矩阵:

# In[17]:

A = lil_matrix((1000, 1000))

A[0, :100] = rand(100)

A[1, 100:200] = A[0, :100]

A.setdiag(rand(1000))

# 转化为 CSR 之后,用 `spsolve` 求解 $Ax=b$:

# In[18]:

A = A.tocsr()

b = rand(1000)

x = spsolve(A, b)

# 转化成正常数组之后求解:

# In[19]:

x_ = solve(A.toarray(), b)

# 查看误差:

# In[20]:

err = norm(x-x_)

err

# ## sparse.find 函数

# 返回一个三元组,表示稀疏矩阵中非零元素的 `(row, col, value)`:

# In[22]:

from scipy import sparse

row, col, val = sparse.find(C)

print(row, col, val)

# ## sparse.issparse 函数

# 查看一个对象是否为稀疏矩阵:

# In[23]:

sparse.issparse(B)

# 或者

# In[24]:

sparse.isspmatrix(B.todense())

# 还可以查询是否为指定格式的稀疏矩阵:

# In[25]:

sparse.isspmatrix_coo(B)

# In[26]:

sparse.isspmatrix_csr(B)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值