📌 目录
scipy.linalg
模块简介- 矩阵运算:矩阵乘法、逆矩阵与转置
- 特征值与特征向量:
eig
和eigvals
- 奇异值分解(SVD):
svd
- 解线性方程组
- 计算行列式与矩阵范数
- 示例:奇异值分解与图像压缩
- 出站链接与参考资料
1. scipy.linalg
模块简介
scipy.linalg
提供了多种线性代数运算,功能丰富,涵盖了矩阵操作、求解线性方程组、特征值分解、奇异值分解等常用算法。它是 SciPy 提供的线性代数库,除了包含 numpy.linalg
中的功能外,还提供了更多的高级操作和优化。
2. 矩阵运算:矩阵乘法、逆矩阵与转置
矩阵乘法
import numpy as np
from scipy.linalg import blas
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
# 使用 NumPy 或 SciPy 进行矩阵乘法
result = np.dot(A, B) # 或者 使用 scipy.linalg.blas.dgemm
print(result)
逆矩阵
from scipy.linalg import inv
A = np.array([[1, 2], [3, 4]])
# 求逆矩阵
A_inv = inv(A)
print(A_inv)
矩阵转置
# 转置矩阵
A_T = A.T
print(A_T)
3. 特征值与特征向量:eig
和 eigvals
求特征值和特征向量
from scipy.linalg import eig
A = np.array([[4, -2], [1, 1]])
# 计算特征值和特征向量
eigenvalues, eigenvectors = eig(A)
print("特征值:", eigenvalues)
print("特征向量:", eigenvectors)
仅求特征值
from scipy.linalg import eigvals
# 仅计算特征值
eigenvalues = eigvals(A)
print("特征值:", eigenvalues)
4. 奇异值分解(SVD):svd
奇异值分解(SVD)用于矩阵的分解,广泛应用于数据降维、推荐系统、图像压缩等领域。
from scipy.linalg import svd
A = np.array([[1, 2], [3, 4], [5, 6]])
# 计算 SVD
U, s, Vh = svd(A)
print("U:", U)
print("s:", s)
print("Vh:", Vh)
U
:左奇异向量s
:奇异值Vh
:右奇异向量(转置)
5. 解线性方程组
SciPy 提供了求解线性方程组的方法,支持矩阵的 LU 分解、QR 分解等。
使用 solve
求解方程组
from scipy.linalg import solve
A = np.array([[3, 2], [1, 2]])
b = np.array([5, 5])
# 求解 Ax = b
x = solve(A, b)
print("解向量 x:", x)
使用 lu
求解方程组
from scipy.linalg import lu, solve
A = np.array([[3, 2], [1, 2]])
b = np.array([5, 5])
# LU 分解
P, L, U = lu(A)
# 使用 L 和 U 解方程
y = solve(L, np.dot(P.T, b))
x = solve(U, y)
print("解向量 x:", x)
6. 计算行列式与矩阵范数
计算行列式
from scipy.linalg import det
A = np.array([[1, 2], [3, 4]])
# 计算行列式
determinant = det(A)
print("行列式:", determinant)
计算矩阵范数
from scipy.linalg import norm
A = np.array([[1, 2], [3, 4]])
# 计算矩阵范数
matrix_norm = norm(A)
print("矩阵范数:", matrix_norm)
7. 示例:奇异值分解与图像压缩
SVD 在图像压缩中的应用非常广泛。通过选择奇异值的前几个最大值,可以有效地减少存储空间,同时保留图像的主要特征。
示例:图像压缩
import imageio
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import svd
# 读取图像
img = imageio.imread('example_image.png', pilmode='L')
# 使用奇异值分解进行压缩
U, s, Vh = svd(img)
# 保留前 k 个奇异值
k = 50
S_k = np.diag(s[:k])
# 近似重构压缩后的图像
img_compressed = np.dot(U[:, :k], np.dot(S_k, Vh[:k, :]))
# 显示原图与压缩图
plt.subplot(1, 2, 1)
plt.imshow(img, cmap='gray')
plt.title("原始图像")
plt.subplot(1, 2, 2)
plt.imshow(img_compressed, cmap='gray')
plt.title(f"压缩图像 (k={k})")
plt.show()
🔗 出站链接与参考资料
📘 官方文档
- SciPy 线性代数模块:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.html svd
函数:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.svd.html
🎓 教程与实战
- SciPy 线性代数教程:
https://scipy-lectures.org/advanced/linear_algebra/ - Real Python 线性代数应用:
https://realpython.com/python-numpy-scipy-linear-algebra/
发表回复