Python 第三方模块 科学计算 SciPy模块7 稀疏矩阵1

十二.Sparse模块
1.创建稀疏矩阵

多数存储形式的稀疏矩阵都支持加////幂运算,一部分存储形式还支持切片

(1)不同存储形式的系数矩阵:

不同存储形式的对比参见:https://www.cnblogs.com/YangZnufe/p/8413374.html

稀疏矩阵的基类:class scipy.sparse.spmatrix([maxprint=50])
  #注意:该类不能被实例化

######################################################################################################################

"分块稀疏行矩阵"(Block Sparse Row Matrix;BSR):class scipy.sparse.bsr_matrix(<arg1>[,shape=None,dtype=None,copy=False,blocksize=None])
"以坐标格式存储的稀疏矩阵"(Sparse Matrix In Coordinate Format;COO):class scipy.sparse.coo_matrix(<arg1>[,shape=None,dtype=None,copy=False])
"压缩稀疏列矩阵"(Compressed Sparse Column Matrix;CSC):class scipy.sparse.csc_matrix(<arg1>[,shape=None,dtype=None,copy=False])
"压缩稀疏行矩阵"(Compressed Sparse Row matrix;CSR):class scipy.sparse.csr_matrix(<arg1>[,shape=None,dtype=None,copy=False])
"以对角格式存储的稀疏矩阵"(Sparse Matrix With Diagonal Storage;DIA):class scipy.sparse.dia_matrix(<arg1>[,shape=None,dtype=None,copy=False])
"基于密钥字典的稀疏矩阵"(Dictionary Of Keys Based Sparse Matrix;DOK):class scipy.sparse.dok_matrix(<arg1>[,shape=None,dtype=None,copy=False])
"基于行链接列表的稀疏矩阵"(Row-Based List Of Lists Sparse Matrix;LIL):class scipy.sparse.lil_matrix(<arg1>[,shape=None,dtype=None,copy=False])

(2)创建特殊的稀疏矩阵:

创建对角线上为1的矩阵:[<sd1>=]scipy.sparse.eye(<m>[,n=<m>,k=0,dtype=<class 'float'>,format=None])
创建单位矩阵:[<sI>=]scipy.sparse.identity(<n>[,dtype='d',format=None])
  #参数说明:
    m,n:分别指定行/列数;均为int
    k:指定值均为1的对角线;int(0为主对角线,>0为上对角线,<0为下对角线)
    dtype:指定数据类型;为dtype/str
    format:指定稀疏矩阵的存储形式;"bsr"/"coo"/"csc"/"csr"/"dia"/"dok"/"lil"
    sd1:返回对角线上为1的矩阵;为sparse matrix
    sI:返回单位矩阵;为sparse matrix

#实例:
>>> sparse.eye(3,k=1).toarray()
array([[0., 1., 0.],
       [0., 0., 1.],
       [0., 0., 0.]])
>>> sparse.identity(3).toarray()
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

######################################################################################################################

创建对角矩阵:[<sd>=]scipy.sparse.diags(<diagonals>[,offsets=0,shape=None,format=None,dtype=None])
           [<sd>=]scipy.sparse.spdiags(<data>,<diags>,<m>,<n>[,format=None])
  #参数说明:其他参数同scipy.sparse.eye()
    diagnols,data:均指定对角线上的元素;均为array-like sequence/int sequence
      #若1条对角线上指定了超出所需的元素,则使用前r个元素
    offset,diags:指定值不为0的对角线;int/int sequence
    shape:指定矩阵的形状;(<m>,<n>),元素均为int,分别指定行/列数
    sd:返回对角矩阵;为sparse matrix

#实例:
>>> sparse.diags([[1,2,3,4],[1,2,3],[1,2]],[0,-1,2]).toarray()
array([[1., 0., 1., 0.],
       [1., 2., 0., 2.],
       [0., 2., 3., 0.],
       [0., 0., 3., 4.]])
>>> sparse.diags([[1,2,3,4],[1,2,3,4],[1,2,3,4]],[0,-1,2]).toarray()
array([[1., 0., 1., 0.],
       [1., 2., 0., 2.],
       [0., 2., 3., 0.],
       [0., 0., 3., 4.]])
>>> sparse.diags([-1,1,2],[0,-1,2],shape=(4,4)).toarray()
array([[-1.,  0.,  2.,  0.],
       [ 1., -1.,  0.,  2.],
       [ 0.,  1., -1.,  0.],
       [ 0.,  0.,  1., -1.]])

######################################################################################################################

创建分块对角矩阵:[<sbd>=]scipy.sparse.block_diag(<mats>[,format=None,dtype=None])
  #参数说明:其他参数同scipy.sparse.eye()
    mats:指定矩阵块;为matrix sequence
    sbd:返回分块对角矩阵;为sparse matrix

######################################################################################################################

返回矩阵的下三角部分:[<sL>=]scipy.sparse.tril(<A>[,k=0,format=None])
返回矩阵的上三角部分:[<sU>=]scipy.sparse.triu(<A>[,k=0,format=None])
  #参数说明:format同scipy.sparse.eye()
    A:指定原矩阵;为sparse matrix/dense matrix
    k:指定以哪条对角线为界划分上/下三角;int
    sL,sU:返回矩阵的下/上三角部分;为sparse matrix

######################################################################################################################

创建分块矩阵:[<sm>=]scipy.sparse.bmat(<blocks>[,format=None,dtype=None])
  #参数说明:其他参数同scipy.sparse.eye()
	blocks:指定矩阵块;为sparse matrix array-like,None表示零矩阵块
	sm:返回分块矩阵;为sparse matrix

#实例:
>>> A=sparse.coo_matrix([[1,2],[3,4]])
>>> B=sparse.coo_matrix([[5],[6]])
>>> C=sparse.coo_matrix([[7]])
>>> sparse.bmat([[A,B],[None,C]]).toarray()
array([[1, 2, 5],
       [3, 4, 6],
       [0, 0, 7]], dtype=int32)

######################################################################################################################

创建非0元素均匀分布的随机矩阵(即元素为随机值的矩阵):[<res>=]scipy.sparse.rand(<m>,<n>[,density=0.01,format='coo',dtype=None,random_state=None])
创建非0元素随机分布的随机矩阵:
  #参数说明:其他参数同scipy.sparse.eye()
    density:指定矩阵的密度(即非0元素的比例);0<=float<=1
    random_state:指定随机数生成器/随机数种子;为numpy.random.RandomState/np.random.Generator/int
    res:返回随机矩阵;为sparse matrix

(3)属性:

数据类型:<sm>.dtype
矩阵形状:<sm>.shape
矩阵维数:<sm>.ndim
非0元素个数:<sm>.nnz
全部非0元素:<sm>.data

###################################################以下为COO特有属性####################################################0元素的行索引:<coo_sm>.row
非0元素的列索引:<coo_sm>.col

###################################################以下为BSR特有属性####################################################

是否有排序索引:<bsr_sm>.has_sorted_indices
BSR格式的索引数组:<bsr_sm>.indices
BSR格式的索引指针数组:<bsr_sm>.indptr
矩阵块的大小:<bsr_sm>.blocksize

(4)方法:

转换存储形式:<sm>.asformat(<format>[,copy=False])
转换数据类型:<sm>.astype(<dtype>[,casting='unsafe',copy=True])
获得对角线上的元素:<sm>.diagonal([k=0])
求点积:<sm>.dot(<other>)
获得指定列:<sm>.getcol(<i>)
获得指定行:<sm>.getrow(<i>)
求指定轴上的最大元素:<sm>.max([axis=None,out=None])
求指定轴上的最小元素:<sm>.min([axis=None,out=None])
求非0元素的行索引:<sm>.nonzero()
转化为多维数组:<sm>.toarray([order=None,out=None])
转换为密集矩阵:<sm>.todense([order=None,out=None])

2.函数
(1)矩阵运算:

求矩阵的"克罗内克积"(Kronecker Product):[<kp>=]scipy.sparse.kron(<A>,<B>[,format=None])
  #参数说明:format同scipy.sparse.eye()
    A,B:指定进行运算的矩阵;为sparse matrix/dense matrix
    kp:返回结果;为sparse matrix

######################################################################################################################

求矩阵的"克罗内克和"(Kronecker Sum):[<ks>=]scipy.sparse.kronsum(<A>,<B>[,format=None])
  #参数说明:其他参数同scipy.sparse.kron()
	ks:返回结果;为sparse matrix

(2)矩阵操作:

水平合并稀疏矩阵:[<sm>=]scipy.sparse.hstack(<blocks>[,format=None,dtype=None])
竖直合并稀疏矩阵:[<sm>=]scipy.sparse.vstack(<blocks>[,format=None,dtype=None])
  #参数说明:同scipy.sparse.bmat()

######################################################################################################################

求非0元素的索引与值:[<I>,<J>,<V>=]scipy.sparse.find(<A>)
  #参数说明:
    A:指定矩阵;为sparse matrix/dense matrix/array-like
    I,J,V:分别返回非0元素的行索引/列索引/;均为array

(3)IO:

将稀疏矩阵保存到npz文件:scipy.sparse.save_npz(<file>,<matrix>[,compressed=True])
  #参数说明:
    file:指定npz文件;file-like object/str(文件路径)
      #如果不以.npz结尾,则会自动补上.npz后缀
    matrix:指定要保存的稀疏矩阵;为sparse matrix(除LIL格式)
    compressed:指定是否压缩文件;bool

######################################################################################################################

从npz文件导入稀疏矩阵:[<result>=]scipy.sparse.load_npz(<file>)
  #参数说明:
	file:指定npz文件;file-like object/str(文件路径)
	  #注意:无论文件后缀如何,都会按npz文件的格式读取
	result:返回稀疏矩阵;为sparse matrix(除LIL格式)

(4)矩阵类型判断:

判断是否为稀疏矩阵:[<r>=]scipy.sparse.issparse(<x>)
                 [<r>=]scipy.sparse.isspmatrix(<x>)
判断是否为CSC格式的稀疏矩阵:[<r>=]scipy.sparse.isspmatrix_csc(<x>)
判断是否为CSR格式的稀疏矩阵:[<r>=]scipy.sparse.isspmatrix_csr(<x>)
判断是否为BSR格式的稀疏矩阵:[<r>=]scipy.sparse.isspmatrix_bsr(<x>)
判断是否为LIL格式的稀疏矩阵:[<r>=]scipy.sparse.isspmatrix_lil(<x>)
判断是否为DOK格式的稀疏矩阵:[<r>=]scipy.sparse.isspmatrix_dok(<x>)
判断是否为COO格式的稀疏矩阵:[<r>=]scipy.sparse.isspmatrix_coo(<x>)
判断是否为DIA格式的稀疏矩阵:[<r>=]scipy.sparse.isspmatrix_dia(<x>)
  #参数说明:
	x:指定对象
	r:返回判断结果;bool

十三.Csgraph子模块
1.简介:

其中定义了基于稀疏矩阵的快速稀疏图算法

2.内容
(1)最短路径问题:

求最短路径:[<dist_matrix>,<predecessors>=]scipy.sparse.csgraph.shortest_path(<csgraph>[,method='auto',directed=True,return_predecessors=False,unweighted=False,overwrite=False,indices=None])
  #参数说明:<csgraph>/directed同scipy.sparse.csgraph.connected_components()
    method:使得寻找最短路径的算法;"auto"(使用4种算法中最好的)/"FW"(Floyd-Warshall algorithm)/"D"(Dijkstra’s algorithm with Fibonacci heaps)/"BF"(Bellman-Ford algorithm)/"J"(Johnson’s algorithm)
    return_predecessors:指定是否返回<predecessors>;bool
    unweighted:True,则使用"无权重距离"(Unweighted Distances),即寻找边最少的路径
               为False,则使用"有权重距离"(Weighted Distances),即寻找权值最小的路径
    overwrite:指定是否用结果覆盖<csgraph>;bool
      #This applies only if method == "FW" and csgraph is a dense, c-ordered array with dtype=float64
    indices:指定要计算的路径;None(所有)/array-like/int
      #仅计算从indices中的节点出发的路径;与method == "FW"不兼容
    dist_matrix:返回各节点间的距离;<n_indices>×<n_nodes> ndarray/1×<n_nodes> ndarray
    predecessors:返回"前件矩阵"(Matrix of Predecessors);<n_indices>×<n_nodes> ndarray/1×<n_nodes> ndarray
      #The N x N matrix of predecessors, which can be used to reconstruct the shortest paths. Row i of the predecessor 
      #matrix contains information on the shortest paths from point i: each entry predecessors[i, j] gives the index 
      #of the previous node in the path from point i to point j. If no path exists between point i and j, then
      #predecessors[i, j] = -9999

######################################################################################################################

使用基于"斐波那契堆"(Fibonacci Heaps)"狄克斯特拉算法"(Dijkstra Algorithm)求最短路径:[<dist_matrix>,<predecessors>,<sources>=]scipy.sparse.csgraph.dijkstra(<csgraph>[,directed=True,indices=None,return_predecessors=False,unweighted=False,limit=np.inf,min_only=False])
  #参数说明:其他参数同scipy.sparse.csgraph.shortest_path()
    limit:指定最大距离(超过的距离被记为np.inf);float>=0
      #较小的limit可减小计算时间
    min_only:True,则寻找从所有节点出发的路径中最短的
             为False,则寻找从每个节点出发的最短路径
    sources:返回到各节点的最短路径的起始节点;1×<n_nodes> ndarray

######################################################################################################################

使用"弗洛伊德算法"(Floyd-Warshall Algorithm)求最短路径:[<dist_matrix>,<predecessors>=]scipy.sparse.csgraph.floyd_warshall(<csgraph>[,directed=True,return_predecessors=False,unweighted=False,overwrite=False])
  #这个中文名...后面的"沃舍尔"去哪了
  #参数说明:同scipy.sparse.csgraph.shortest_path()

######################################################################################################################

使用"贝尔曼-福特算法"(Bellman-Ford Algorithm)求最短路径:[<dist_matrix>,<predecessors>=]scipy.sparse.csgraph.bellman_ford(<csgraph>[,directed=True,indices=None,return_predecessors=False,unweighted=False)
  #参数说明:同scipy.sparse.csgraph.shortest_path()

######################################################################################################################

使用"约翰逊算法"(Johnson’s Algorithm)求最短路径:[<dist_matrix>,<predecessors>=]scipy.sparse.csgraph.johnson(<csgraph>[,directed=True,indices=None,return_predecessors=False,unweighted=False)
  #参数说明:同scipy.sparse.csgraph.shortest_path()

(2)深度优先与广度优先:

求从指定节点开始的"广度优先序列"(Breadth-First Ordering):[<node_array>,<predecessors>=]scipy.sparse.csgraph.breadth_first_order(<csgraph>,<i_start>[,directed=True,return_predecessors=True])
  #参数说明:其他参数同scipy.sparse.csgraph.shortest_path()
	i_start:指定起始节点;int
	node_array:返回广度优先序列;为ndarray
	predecessors:返回广度优先树的前件矩阵;为ndarray
	  #If node i is in the tree, then its parent is given by predecessors[i]. If node i is not in the tree (and for 
	  #the parent node) then predecessors[i] = -9999

######################################################################################################################

求从指定节点开始的"深度优先序列"(Depth-First Ordering):[<node_array>,<predecessors>=]scipy.sparse.csgraph.depth_first_order(<csgraph>,<i_start>[,directed=True,return_predecessors=True])
  #参数说明:其他参数同scipy.sparse.csgraph.breadth_first_order()
    node_array:返回深度优先序列;为ndarray
	predecessors:返回深度优先树的前件矩阵;为ndarray
	  #If node i is in the tree, then its parent is given by predecessors[i]. If node i is not in the tree (and for the 
	  #parent node) then predecessors[i] = -9999.

######################################################################################################################"广度优先树"(Breadth-First Tree):[<cstree>=]scipy.sparse.csgraph.breadth_first_tree(<csgraph>,<i_start>[,directed=True])
  #参数说明:其他参数同scipy.sparse.csgraph.breadth_first_order()
	cstree:返回广度优先树;为N×N CSR sparse matrix

######################################################################################################################"深度优先树"(Depth-First Tree):[<cstree>=]scipy.sparse.csgraph.depth_first_tree(<csgraph>,<i_start>[,directed=True])
  #参数说明:其他参数同scipy.sparse.csgraph.breadth_first_order()
	cstree:返回深度优先树;为N×N CSR sparse matrix

(3)转换:

通过前件矩阵建立距离矩阵:[<dist_matrix>=]scipy.sparse.csgraph.construct_dist_matrix(<graph>,<predecessors>[,directed=True,null_value=np.inf])
  #参数说明:其他参数同scipy.sparse.csgraph.breadth_first_order()
    graph:指定图;为N×N array-like/N×N sparse matrix
    predecessors:指定前件矩阵;为N×N array-like
    null_value:指定未互相连接的节点间的值;float
    dist_matrix:返回距离矩阵;为N×N ndarray

######################################################################################################################

将密集矩阵转换为稀疏图:[<csgraph>=]scipy.sparse.csgraph.csgraph_from_dense(<graph>[,null_value=0,nan_null=True,infinity_null=True])
  #参数说明:
    graph:指定原矩阵;为N×N array-like
    null_value:指定非连接的节点间的值;float/None
    infinity_null:指定是否将无穷值作为null edge来处理;bool
    nan_null:指定是否将NaN作为非连接节点间的值来处理;bool
    csgraph:返回稀疏图;为N×N CSR sparse matrix

######################################################################################################################"掩码数组"(Masked Array)转换为稀疏图:[<csgraph>=]scipy.sparse.csgraph.csgraph_from_masked(<graph>)
  #参数说明:其他参数同scipy.sparse.csgraph.csgraph_from_dense()
    graph:指定原图;为N×N np.ma.MaskedArray

######################################################################################################################

将密集图转换为掩码数组:[<csgraph>=]scipy.sparse.csgraph.csgraph_masked_from_dense(<graph>[,null_value=0,nan_null=True,infinity_null=True,copy=True])
  #参数说明:其他参数同scipy.sparse.csgraph.csgraph_from_dense()
    csgraph:返回图的掩码数组表示;为np.ma.MaskedArray

######################################################################################################################

将稀疏图转换为密集图[<graph>=]scipy.sparse.csgraph.csgraph_to_dense(<csgraph>[,null_value=0])
  #参数说明:其他参数同scipy.sparse.csgraph.csgraph_from_dense()
    csgraph:指定原稀疏图;为CSR sparse matrix/CSC sparse matrix/LIL sparse matrix
    graph:返回密集图;为ndarray

######################################################################################################################

将稀疏图转换为掩码数组:[<graph>=]scipy.sparse.csgraph.csgraph_to_masked(<csgraph>)
  #参数说明:<csgraph>同scipy.sparse.csgraph.csgraph_to_dense()
    graph:返回图的掩码数组表示;为np.ma.MaskedArray

######################################################################################################################

创建树:[<cstree>=]scipy.sparse.csgraph.reconstruct_path(<csgraph>,<predecessors>[,directed=True])
  #参数说明:其他参数同scipy.sparse.csgraph.construct_dist_matrix()
    csgraph:指定图;为N×N array-like/N×N sparse matrix
    predecessors:指定前件矩阵;1×N array-like
    cstree:返回树;为CSR sparse matrix

猜你喜欢

转载自blog.csdn.net/weixin_46131409/article/details/114653117
今日推荐