8.scipy Sparse
title: "8.scipy-sparse" date: 2026-05-24T14:11:23Z
1%matplotlib inline
2import numpy as np
3import pylab as pl
4from scipy import sparse
5from scipy.sparse import csgraph
稀疏矩阵-sparse
稀疏矩阵的储存形式
1from scipy import sparse
2a = sparse.dok_matrix((10, 5))
3
4a[2, 3] = 1.0
5a[3, 3] = 2.0
6a[4, 3] = 3.0
7print(a.keys())
8print(a.values())
dict_keys([(2, 3), (3, 3), (4, 3)])
dict_values([1.0, 2.0, 3.0])
1b = sparse.lil_matrix((10, 5))
2b[2, 3] = 1.0
3b[3, 4] = 2.0
4b[3, 2] = 3.0
5print(b.data)
6print(b.rows)
[list([]) list([]) list([1.0]) list([3.0, 2.0]) list([]) list([]) list([])
list([]) list([]) list([])]
[list([]) list([]) list([3]) list([2, 4]) list([]) list([]) list([])
list([]) list([]) list([])]
1row = [2, 3, 3, 2]
2col = [3, 4, 2, 3]
3data = [1, 2, 3, 10]
4c = sparse.coo_matrix((data, (row, col)), shape=(5, 6))
5print (c.col, c.row, c.data)
6print (c.toarray())
[3 4 2 3] [2 3 3 2] [ 1 2 3 10]
[[ 0 0 0 0 0 0]
[ 0 0 0 0 0 0]
[ 0 0 0 11 0 0]
[ 0 0 3 0 2 0]
[ 0 0 0 0 0 0]]
矩阵向量相乘
1 import numpy as np
2from scipy.sparse import csr_matrix
3A = csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
4v = np.array([1, 0, -1])
5A.dot(v)
array([ 1, -3, -1], dtype=int32)
示例1
构造一个1000x1000 lil_matrix并添加值:
1from scipy.sparse import lil_matrix
2from scipy.sparse.linalg import spsolve
3from numpy.linalg import solve, norm
4from numpy.random import rand
1A = lil_matrix((1000, 1000))
2A[0, :100] = rand(100)
3A[1, 100:200] = A[0, :100]
4A.setdiag(rand(1000))
现在将其转换为CSR格式,并求解$A x = b$的$x$:
1A = A.tocsr()
2b = rand(1000)
3x = spsolve(A, b)
将其转换为密集矩阵并求解,并检查结果是否相同:
1x_ = solve(A.toarray(), b)
现在我们可以使用以下公式计算错误的范数:
1err = norm(x-x_)
2err < 1e-10
True
示例2
构造COO格式的矩阵:
1from scipy import sparse
2from numpy import array
3I = array([0,3,1,0])
4J = array([0,3,1,2])
5V = array([4,5,7,9])
6A = sparse.coo_matrix((V,(I,J)),shape=(4,4))
注意,索引不需要排序。
转换为CSR或CSC时,将对重复的(i,j)条目进行求和。
1I = array([0,0,1,3,1,0,0])
2J = array([0,2,1,3,1,0,0])
3V = array([1,1,1,1,1,1,1])
4B = sparse.coo_matrix((V,(I,J)),shape=(4,4)).tocsr()
这对于构造有限元刚度矩阵和质量矩阵是有用的。