SciPy - 条件数
In SciPy 中,Condition Number(条件数)量化了矩阵对其输入或元素的小幅变化的敏感性。它是评估线性系统、本征值问题和矩阵计算数值稳定性的关键指标。矩阵 A 的条件数定义如下 −
κ(A) = ‖ A ‖ ċ ‖ A-1 ‖
其中 A 是矩阵范数,例如 2-norm、Frobenius norm,而 A-1 是逆矩阵的范数。较高的条件数表明矩阵是病态的,这意味着输入的小变化可能导致输出的大误差。对于奇异矩阵,条件数是无穷大的,因为逆矩阵不存在。
关键概念
以下是条件数的关键概念 −
- Condition number: 一个指示矩阵敏感性的值。较大的条件数,例如 > 106,表明矩阵是病态的,矩阵或输入中的小误差可能导致计算解中的大误差。
- Norm: 条件数取决于所使用的范数。常见的范数包括 2-norm(谱范数)、1-norm 和 Frobenius norm。
条件数解释
以下是 SciPy 中条件数的解释 −
- 小的条件数(接近 1): 矩阵是良条件的,这意味着输入数据的小变化会导致输出的小变化。方程组在数值上是稳定的。
- 大的条件数: 矩阵是病态的。输入中的小变化或误差可能导致解中的大误差。这通常发生在矩阵接近奇异时,即矩阵没有满秩或具有接近零的奇异值。
示例 1
矩阵的条件数是最大奇异值与最小奇异值的比率。由于没有预定义的函数来实现条件数,我们可以使用 scipy.linalg.svd() 函数手动实现条件数的计算。以下是实现条件数的示例 −
import numpy as np
from scipy.linalg import svd
# Example matrix (well-conditioned)
A_well = np.array([[2, 1], [1, 3]])
# Compute Singular Value Decomposition (SVD)
U, s, Vh = svd(A_well)
# Compute the condition number: max singular value / min singular value
condition_number = s[0] / s[-1]
print(f"Condition number (well-conditioned matrix): {condition_number}")
# Example matrix (ill-conditioned)
A_ill = np.array([[1, 2], [2, 4]])
# Compute Singular Value Decomposition (SVD)
U, s, Vh = svd(A_ill)
# Compute the condition number
condition_number_ill = s[0] / s[-1]
print(f"Condition number (ill-conditioned matrix): {condition_number_ill}")
以下是用于实现条件数的 scipy.linalg.svd() 函数的输出 −
Condition number (well-conditioned matrix): 2.6180339887498953 Condition number (ill-conditioned matrix): 2.5175887275607884e+16
示例 2
以下是使用 scipy.linalg.svd() 函数一起实现良条件矩阵和病态矩阵的示例 −
import numpy as np
from scipy.linalg import svd
# Well-conditioned matrix
A_well = np.array([[2, 1], [1, 3]])
# Ill-conditioned matrix
A_ill = np.array([[1, 2], [2, 4]])
# Compute singular values and condition numbers for both matrices
def compute_condition_number(A):
# Compute singular values using SVD
U, S, Vt = svd(A)
# Condition number is the ratio of the largest to the smallest singular value
return S[0] / S[-1]
# Condition numbers
condition_number_well = compute_condition_number(A_well)
condition_number_ill = compute_condition_number(A_ill)
print(f"Singular values (well-conditioned matrix): {svd(A_well)[1]}")
print(f"Condition number (well-conditioned matrix): {condition_number_well}")
print(f"Singular values (ill-conditioned matrix): {svd(A_ill)[1]}")
print(f"Condition number (ill-conditioned matrix): {condition_number_ill}")
以下是用于实现良条件矩阵和病态矩阵的 scipy.linalg.svd() 函数的输出 −
Singular values (well-conditioned matrix): [3.61803399 1.38196601] Condition number (well-conditioned matrix): 2.6180339887498953 Singular values (ill-conditioned matrix): [5.00000000e+00 1.98602732e-16] Condition number (ill-conditioned matrix): 2.5175887275607884e+16
条件数与求解线性方程组
在求解线性方程组 Ax=b 时,矩阵 A 的条件数 cond(A) 提供了解 x 对矩阵 A 或向量 b 小变化的响应变化程度的估计。
- 如果条件数较低,则求解系统是稳定的,A 或 b 的小变化只会导致 x 的小变化。
- 如果条件数较高,则解可能对误差高度敏感。A 或 b 的小变化可能导致 x 的大变化。