在 true_divide 中遇到 Gram_Schimdt 算法的无效值
invalid value encountered in true_divide for Gram_Schimdt algorithm
我试图使用以下函数实现 Gram-Schimdt。但是,代码中似乎有一个零分频器。但是我不知道怎么解决。
def gs(A):
x = A.shape[0]
y = A.shape[1]
U = np.zeros((x,y))
U[:,1] = A[:,1]/np.linalg.norm(A[:,1])
for i in range(1,y):
U[:,i] = A[:,i]
for j in range(0,i):
U[:,i] = U[:,i] - U[:,j].dot(U[:,i])*U[:,j]/(U[:,j].dot(U[:,j]))
U[:,i] = U[:,i]/np.linalg.norm(U[:,i])
return U
错误信息:
/var/folders/tr/ssszhd_x03jdz162mg0j01vm0000gn/T/ipykernel_39952/685295545.py:9: RuntimeWarning: invalid value encountered in true_divide
U[:,i] = U[:,i] - U[:,j].dot(U[:,i])*U[:,j]/(U[:,j].dot(U[:,j]))
问题出在初始化
U[:,1] = A[:,1]/np.linalg.norm(A[:,1])
第一列是 U[:,0]
,因为您要分配给 U[:,1]
,所以 U[:,0]
将保持全零,并且循环将用 zero-divisions 填充矩阵.
修正那条线就可以了
def gs(A):
x = A.shape[0]
y = A.shape[1]
U = np.zeros((x,y))
U[:,0] = A[:,0]/np.linalg.norm(A[:,0])
for i in range(1,y):
U[:,i] = A[:,i]
for j in range(0,i):
U[:,i] = U[:,i] - U[:,j].dot(U[:,i])*U[:,j]/(U[:,j].dot(U[:,j]))
U[:,i] = U[:,i]/np.linalg.norm(U[:,i])
return U
# test
A = gs(np.random.rand(100, 50))
assert np.allclose(A.T @ A, np.eye(50)) # check the results
我试图使用以下函数实现 Gram-Schimdt。但是,代码中似乎有一个零分频器。但是我不知道怎么解决。
def gs(A):
x = A.shape[0]
y = A.shape[1]
U = np.zeros((x,y))
U[:,1] = A[:,1]/np.linalg.norm(A[:,1])
for i in range(1,y):
U[:,i] = A[:,i]
for j in range(0,i):
U[:,i] = U[:,i] - U[:,j].dot(U[:,i])*U[:,j]/(U[:,j].dot(U[:,j]))
U[:,i] = U[:,i]/np.linalg.norm(U[:,i])
return U
错误信息:
/var/folders/tr/ssszhd_x03jdz162mg0j01vm0000gn/T/ipykernel_39952/685295545.py:9: RuntimeWarning: invalid value encountered in true_divide
U[:,i] = U[:,i] - U[:,j].dot(U[:,i])*U[:,j]/(U[:,j].dot(U[:,j]))
问题出在初始化
U[:,1] = A[:,1]/np.linalg.norm(A[:,1])
第一列是 U[:,0]
,因为您要分配给 U[:,1]
,所以 U[:,0]
将保持全零,并且循环将用 zero-divisions 填充矩阵.
修正那条线就可以了
def gs(A):
x = A.shape[0]
y = A.shape[1]
U = np.zeros((x,y))
U[:,0] = A[:,0]/np.linalg.norm(A[:,0])
for i in range(1,y):
U[:,i] = A[:,i]
for j in range(0,i):
U[:,i] = U[:,i] - U[:,j].dot(U[:,i])*U[:,j]/(U[:,j].dot(U[:,j]))
U[:,i] = U[:,i]/np.linalg.norm(U[:,i])
return U
# test
A = gs(np.random.rand(100, 50))
assert np.allclose(A.T @ A, np.eye(50)) # check the results