左矩阵除法与Numpy

2024-04-27 15:42:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将包含\运算符的代码从Matlab(Octave)转换为Python。示例代码

B = [2;4]
b = [4;4]
B \ b

这样做可以产生1.2作为答案。使用此网页

http://mathesaurus.sourceforge.net/matlab-numpy.html

我把它翻译成:

import numpy as np
import numpy.linalg as lin
B = np.array([[2],[4]])
b = np.array([[4],[4]])
print lin.solve(B,b)

这给了我一个错误:

numpy.linalg.linalg.LinAlgError: Array must be square

为什么Matlab \对B使用非平方矩阵?

有什么解决办法吗?


Tags: 答案代码importnumpyhttp网页示例as
3条回答

当使用\运算符时,根据所涉及矩阵的形状,Matlab实际上会执行许多不同的操作(有关详细信息,请参见here)。在您的示例中,Matlab返回的是最小二乘解,而不是直接求解线性方程,就像使用平方矩阵一样。要在numpy中获得相同的行为,请执行以下操作:

import numpy as np
import numpy.linalg as lin
B = np.array([[2],[4]])
b = np.array([[4],[4]])
print np.linalg.lstsq(B,b)[0]

它应该给你和Matlab一样的解决方案。

MathWorks documentation开始左矩阵除法:

If A is an m-by-n matrix with m ~= n and B is a column vector with m components, or a matrix with several such columns, then X = A\B is the solution in the least squares sense to the under- or overdetermined system of equations AX = B. In other words, X minimizes norm(A*X - B), the length of the vector AX - B.

在numpy中等价于np.linalg.lstsq

In [15]: B = np.array([[2],[4]])

In [16]: b = np.array([[4],[4]])

In [18]: x,resid,rank,s = np.linalg.lstsq(B,b)

In [19]: x
Out[19]: array([[ 1.2]])

可以形成左逆:

import numpy as np
import numpy.linalg as lin
B = np.array([[2],[4]])
b = np.array([[4],[4]])

B_linv = lin.solve(B.T.dot(B), B.T)
c = B_linv.dot(b)
print('c\n', c)

结果:

c
 [[ 1.2]]

实际上,我们可以只运行一次解算器,而不形成逆解,如下所示:

c = lin.solve(B.T.dot(B), B.T.dot(b))
print('c\n', c)

结果:

c
 [[ 1.2]]

。。。。像以前一样

为什么?因为:

我们有:

enter image description here

乘以B.T,得到:

enter image description here

现在,B.T.dot(B)是平方的,全秩,有一个逆。因此我们可以乘以B.T.dot(B)的逆,或者使用解算器,如上所述,得到c

相关问题 更多 >