numpy 自定义内积空间中使用nympy/sympy的Gram施密特算法

nafvub8i  于 2023-06-06  发布在  其他
关注(0)|答案(1)|浏览(153)

我正在尝试使用numpy或sympy为一个特殊的内积空间(所以不是欧几里得空间)编写一个Gram施密特算法。内积空间是

向量是

def inner_product(x, y):
    return x[0]*y[0] + 2*x[1]*y[1] + x[2]*y[2]

def gram_schmidt(V):
 U = []
 for i in range(len(V)):
   # start with the current vector
   u = V[i]
   for j in range(i):
     # subtract the projection of V[i] onto each U[j]
     proj = (inner_product(V[i], U[j]) / inner_product(U[j], U[j])) * U[j]
     u = u - proj
   # normalize
   U.append(u / np.linalg.norm(u))
 return np.array(U)

V = np.array([[1, 3, 4], [1, 2, 1], [1, 1, 2]])
U = gram_schmidt(V)
print(U)

如果算法能够打印出流程的所有步骤,那就太好了

2ic8powd

2ic8powd1#

请参阅Gram-Schmidt以了解确切的算法。

请注意,你为缩放所取的范数是欧几里得范数,所以很明显这会成为一个问题。同样,如果你在每一步都将其“归一化”,你就不需要在减法过程中将其归一化。

不管怎样,我是这样做的:

import numpy as np

def inner_product(x, y):
    return x[0]*y[0] + 2*x[1]*y[1] + x[2]*y[2]

# Gram Schmidt:
# Take in a list of vectors
def gram_schmidt(V):
    # Orthogonalized, To Be Returned
    orthogonal = []

    # At each step, take vector
    for i in range(len(V)):
        v = copy.deepcopy(V[i])
        
        # Subtract off the "components" from current orthogonal set.
        for j in range(i):
            v = v - inner_product(orthogonal[j], v) * orthogonal[j]
        
        # Normalization
        v = v / ((inner_product(v, v))**0.5)
        orthogonal.append(v)
    
    return orthogonal

# Try the following:
V = [np.array([1,1,1]), np.array([3,2,1]), np.array([4,1,2])]
GS = gram_schmidt(V)
# Should print roughly 0 and 1 respectively
print(inner_product(GS[0], GS[1]))
print(inner_product(GS[0], GS[0]))

相关问题