A = np.array([[2,-1],[-1,2],[0,-1]])
q, r = np.linalg.qr(A, 'complete')
print(q)
print(r)
# The line below will raise error: numpy.linalg.LinAlgError: Last 2 dimensions of the array must be square
print(np.dot(np.linalg.inv(r), q.T))
# Mathmatically, I think it should output something similar to the following code, if im not wrong. The following code should be able to run
print(np.dot(np.linalg.inv(np.dot(A.T, A)), A.T))
我想让这段代码工作,但得到这个错误:
numpy.linalg。LinAlgError:数组的最后两个维度必须是广场
我知道第二个矩阵不是平方的,但是无论如何我可以使这个代码工作吗?例如,有没有一种方法可以绕过这个或者把矩阵变成平方?
In [117]: q
Out[117]:
array([[-0.89442719, -0.35856858, 0.26726124],
[ 0.4472136 , -0.71713717, 0.53452248],
[-0. , 0.5976143 , 0.80178373]])
In [118]: r # same shape as A, (3,2) as per docs
Out[118]:
array([[-2.23606798, 1.78885438],
[ 0. , -1.67332005],
[ 0. , 0. ]])
r
没有0的行是可逆的:
In [120]: np.linalg.inv(r[:2])
Out[120]:
array([[-0.4472136 , -0.47809144],
[-0. , -0.5976143 ]])
我们可以用q
的一部分来dot
它:
In [130]: np.dot(np.linalg.inv(r[:2]),q.T[:2])
Out[130]:
array([[ 0.57142857, 0.14285714, -0.28571429],
[ 0.21428571, 0.42857143, -0.35714286]])
匹配:
In [131]: np.dot(np.linalg.inv(np.dot(A.T, A)), A.T)
Out[131]:
array([[ 0.57142857, 0.14285714, -0.28571429],
[ 0.21428571, 0.42857143, -0.35714286]])
pinv
In [5]: np.linalg.pinv(r)
Out[5]:
array([[-0.4472136 , -0.47809144, 0. ],
[ 0. , -0.5976143 , 0. ]])
In [6]: np.dot(np.linalg.pinv(r),q.T)
Out[6]:
array([[ 0.57142857, 0.14285714, -0.28571429],
[ 0.21428571, 0.42857143, -0.35714286]])