施密特正交化 GramSchmidt
施密特正交化的原名是 Gram–Schmidt process,是由Gram和schmidt两个人一起发明的,但是后来因为施密特名气更大,所以该方法被简记为施密特正交化。
借用 《线性代数》P117-例2 的例子来运行代码。
\[a_1 = (1,2,-1)^T \\
a_2 = (-1,3,1)^T \\
a_3 = (4,-1,0)^T
\]
a_2 = (-1,3,1)^T \\
a_3 = (4,-1,0)^T
\]
正交化后:
\[a_1 = (1,2,-1)^T \\
a_2 = \frac{5}{3}(-1,1,1)^T \\
a_3 = 2(1,0,1)^T
\]
a_2 = \frac{5}{3}(-1,1,1)^T \\
a_3 = 2(1,0,1)^T
\]
单位化后:
\[a_1 = \frac{1}{\sqrt{6}}(1,2,-1)^T \\
a_2 = \frac{1}{\sqrt{3}}(-1,3,1)^T \\
a_3 = \frac{1}{\sqrt{2}}(4,-1,0)^T
\]
a_2 = \frac{1}{\sqrt{3}}(-1,3,1)^T \\
a_3 = \frac{1}{\sqrt{2}}(4,-1,0)^T
\]
代码实现
python3 的 sympy 包实现了 GramSchmidt 方法。
from sympy.matrices import Matrix, GramSchmidt
l = [Matrix([1,2,-1]), Matrix([-1,3,1]), Matrix([4,1,0])]
o = GramSchmidt(l)
计算结果如下:
[Matrix([
[ 1],
[ 2],
[-1]]),
Matrix([
[-5/3],
[ 5/3],
[ 5/3]]),
Matrix([
[2],
[0],
[2]])]
单位化也就是在调用函数的时候传入参数。
from sympy.matrices import Matrix, GramSchmidt
l = [Matrix([1,2,-1]), Matrix([-1,3,1]), Matrix([4,1,0])]
o = GramSchmidt(l, True)
计算结果如下:
[Matrix([
[ sqrt(6)/6],
[ sqrt(6)/3],
[-sqrt(6)/6]]),
Matrix([
[-sqrt(3)/3],
[ sqrt(3)/3],
[ sqrt(3)/3]]),
Matrix([
[sqrt(2)/2],
[ 0],
[sqrt(2)/2]])]
sympy.Matrix 与 Numpy 的互操作
Matrix 转 Numpy.array
import numpy as np
from sympy.matrices import Matrix, GramSchmidt
l = [Matrix([1,2,-1]), Matrix([-1,3,1]), Matrix([4,1,0])]
o = GramSchmidt(l, True)
m = np.array(o)
内积计算
(m[0] * m[1]).sum()
References
[1] https://en.wikipedia.org/wiki/Gram–Schmidt_process
[2] GramSchmidt. sympy: https://docs.sympy.org/latest/modules/matrices/matrices.html?highlight=gramschmidt#sympy.matrices.dense.GramSchmidt