python/sympy计算施密特正交化向量

版权声明:本文为博主ouening原创文章,未经博主允许不得恶意复制转载,需要注明出处,尊重知识成果!技术交流请联系[email protected]! https://blog.csdn.net/ouening/article/details/83279894

sympy的符号计算功能很强大,学习矩阵分析,重温了线性代数中施密特正交化的方法,正好可以用sympy解决一些计算问题。施密特正交化,也称 Gram-Schmidt 正交化过程 (Gram–Schmidt Orthogonalization Procedure). 该⽅法以Jørgen P. Gram 和 Erhard Schmidt 命名, 它更早出现在拉普拉斯和柯西的⽂章中[1],步骤如下:

(1) β 1 = α 1 \beta_1=\alpha_1
(2) β j = α j ( β 1 , α j ) ( β 1 , β 1 ) β 1 ( β 2 , α j ) ( β 2 , β 2 ) β 2 ( β j 1 , α j ) ( β j 1 , β j 1 ) β j 1 \beta_j=\alpha_j-\frac{(\beta_1,\alpha_j)}{(\beta_1,\beta_1)}\beta_1-\frac{(\beta_2,\alpha_j)}{(\beta_2,\beta_2)}\beta_2-\frac{(\beta_{j-1},\alpha_j)}{(\beta_{j-1},\beta_{j-1})}\beta_{j-1}
(3) η j = β j β j , j = 1 , 2 , . . . , m \eta_j=\frac{\beta_j}{||\beta_j||},j=1,2,...,m

例如求3个无关列向量的正交向量组:
α 1 = ( 1 , 2 , 3 ) T \alpha_1=(1,2,3)^T , α 2 = ( 2 , 1 , 3 ) T \alpha_2=(2,1,3)^T , α 3 = ( 3 , 2 , 1 ) T \alpha_3=(3,2,1)^T
手动计算可以按照前面的步骤求解,下面介绍sympy相关函数,很简单,如下面代码所示:

from sympy import *

L = [Matrix([1,2,3]), Matrix([2,1,3]), Matrix([3,2,1])]

o1=GramSchmidt(L)

o1
Out[4]: 
[Matrix([
 [1],
 [2],
 [3]]), Matrix([
 [15/14],
 [ -6/7],
 [ 3/14]]), Matrix([
 [ 4/3],
 [ 4/3],
 [-4/3]])]

o2=GramSchmidt(L,True) # 标准化

o2
Out[6]: 
[Matrix([
 [  sqrt(14)/14],
 [   sqrt(14)/7],
 [3*sqrt(14)/14]]), Matrix([
 [ 5*sqrt(42)/42],
 [-2*sqrt(42)/21],
 [   sqrt(42)/42]]), Matrix([
 [ sqrt(3)/3],
 [ sqrt(3)/3],
 [-sqrt(3)/3]])]

函数GramSchmidt(vlist, orthonormal=False),将参数orthonormal设为True 计算结果便是标准正交基,记作:
( α i , α j ) = δ i j (\alpha_i,\alpha_j)=\delta_{ij}

注意,scipy.linalg包也提供了函数orth()来计算标准正交基,但是根据文档介绍其使用的方法是SVD奇异值分解,所以求解结果和sympy的不一样

from scipy.linalg import *
import numpy as np

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

a
Out[7]: 
array([[1, 2, 3],
       [2, 1, 3],
       [3, 2, 1]])

a=a.T

a
Out[9]: 
array([[1, 2, 3],
       [2, 1, 2],
       [3, 3, 1]])

orthogonal_procrustes?

orth(a)
Out[11]: 
array([[-0.56525513,  0.68901653,  0.45358886],
       [-0.47238331,  0.18041382, -0.86273105],
       [-0.67626966, -0.70193096,  0.22350007]])

参考资料
[1] 黄正华 武汉大学http://aff.whu.edu.cn/huangzh/

猜你喜欢

转载自blog.csdn.net/ouening/article/details/83279894