我有以下用于 QR 分解的 python 代碼。在第 行Q[:,i] = u / norm,我收到標題中提到的錯誤。請問有人可以幫忙嗎?
Q具有形狀 (3,3),u預計具有形狀 (3,1)norm是標量
錯誤資訊是:
could not broadcast input array from shape (3,1) into shape (3,)
預期輸出是形狀為 (3,3) 的矩陣 Q。
import numpy as np
def QRfactorization(A):
# getting the size of the matrix
N = len(A)
# preallocating Q
Q = np.zeros((N, N))
for i in range(N):
u = A[:,i]
for j in range(i):
# calculating the projection
h = np.vdot(u,Q[:,j])
u = u - h*Q[:,j]
norm = np.linalg.norm(u)
Q[:,i] = u / norm
#getting R matrix
R = Q.T*A
return Q , R
def main():
# input is an square matrix A
A = np.matrix([[1,2,3],[4,5,6],[1,2,3]])
Q = QRfactorization(A)
print(Q)
main()
uj5u.com熱心網友回復:
使用的numpy.matrix是沮喪,并且使用numpy.array還解決這個問題:
def main():
# input is an square matrix A
A = np.array([[1,2,3],[4,5,6],[1,2,3]])
Q = QRfactorization(A)
print(Q)
uj5u.com熱心網友回復:
你可以避免自己寫,直接用 numpy.linalg.qr
https://numpy.org/doc/stable/reference/generated/numpy.linalg.qr.html
def main():
# input is an square matrix A
A = np.matrix([[1,2,3],[4,5,6],[1,2,3]])
q, r = np.linalg.qr(A)
print(q)
print(r)
請注意,如果 R 部分對您的結果很重要,則您沒有完全/正確地計算 R 部分,因為它應該是一個上三角矩陣
結果與@Nils Werner.array()對您的方法的更改
(結果合并到一個陣列中)
(array([[ 0.23570226, 0.66666667, -0.23570226],
[ 0.94280904, -0.33333333, -0.94280904],
[ 0.23570226, 0.66666667, -0.23570226]]), array([[ 0.23570226, 1.88561808, 0.70710678],
[ 2.66666667, -1.66666667, 4. ],
[-0.23570226, -1.88561808, -0.70710678]]))
結果來自天真np.linalg.qr(“完整”和“減少”相同mode)
[[-2.35702260e-01 6.66666667e-01 -7.07106781e-01]
[-9.42809042e-01 -3.33333333e-01 2.22044605e-16]
[-2.35702260e-01 6.66666667e-01 7.07106781e-01]]
[[-4.24264069 -5.65685425 -7.07106781]
[ 0. 1. 2. ]
[ 0. 0. 0. ]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/340798.html
上一篇:如何將陣列字串轉換為字串陣列?
