numpy 或 scipy 中的左逆?
我正在尝试使用 numpy 或 scipy 获取 python 中非方阵的左逆矩阵。 如何将以下 Matlab 代码转换为 Python?
>> A = [0,1; 0,1; 1,0]
A =
0 1
0 1
1 0
>> y = [2;2;1]
y =
2
2
1
>> A\y
ans =
1.0000
2.0000
Matlab 中是否有与左逆 \
运算符等效的 numpy 或 scipy?
I am trying to obtain the left inverse of a non-square matrix in python using either numpy or scipy.
How can I translate the following Matlab code to Python?
>> A = [0,1; 0,1; 1,0]
A =
0 1
0 1
1 0
>> y = [2;2;1]
y =
2
2
1
>> A\y
ans =
1.0000
2.0000
Is there a numpy or scipy equivalent of the left inverse \
operator in Matlab?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用
linalg.lstsq(A,y)
,因为A
不是正方形。有关详细信息,请参阅此处。如果A
是正方形,则可以使用linalg.solve(A,y)
,但在您的情况下则不然。Use
linalg.lstsq(A,y)
sinceA
is not square. See here for details. You can uselinalg.solve(A,y)
ifA
is square, but not in your case.lesssq 函数,
这是一种处理稀疏矩阵的方法(根据您的评论,这是您想要的),它使用优化包中生成的
它有点难看,因为我必须根据什么来匹配形状想要最小平方。也许其他人知道如何使其变得更加整洁。
我还尝试通过使用 LinearOperators 来处理 scipy.sparse.linalg 中的函数,但无济于事。问题是所有这些函数都只能处理平方函数。如果有人找到一种方法可以做到这一点,我也想知道。
Here is a method that will work with sparse matrices (which from your comments is what you want) which uses the leastsq function from the optimize package
generates
It is kind of ugly because of how I had to get the shapes to match up according to what leastsq wanted. Maybe someone else knows how to make this a little more tidy.
I have also tried to get something to work with the functions in scipy.sparse.linalg by using the LinearOperators, but to no avail. The problem is that all of those functions are made to handle square functions only. If anyone finds a way to do it that way, I would like to know as well.
对于那些希望解决大型稀疏最小二乘问题的人:
我已将 LSQR 算法添加到 SciPy 中。在下一个版本中,您将能够执行以下操作:
返回答案
[1, 2]
。如果您想在不升级 SciPy 的情况下使用此新功能,您可以从代码存储库下载
lsqr.py
,网址为http://projects.scipy.org/scipy/browser/trunk/scipy/sparse/linalg/isolve/lsqr.py< /a>
For those who wish to solve large sparse least squares problems:
I have added the LSQR algorithm to SciPy. With the next release, you'll be able to do:
which returns the answer
[1, 2]
.If you'd like to use this new functionality without upgrading SciPy, you may download
lsqr.py
from the code repository athttp://projects.scipy.org/scipy/browser/trunk/scipy/sparse/linalg/isolve/lsqr.py
您还可以查找伪逆函数的等效项
pinv
在numpy/scipy
中,作为其他答案的替代方案。You can also look for the equivalent of the pseudo-inverse function
pinv
innumpy/scipy
, as an alternative to the other answers that is.您可以使用矩阵计算来计算左逆:(
为什么?因为:
)
测试:
结果:
You can calculate the left inverse using matrix calculations:
(Why? Because:
)
Test:
Result:
我还没有测试过它,但根据此网页,它是:
I haven't tested it, but according to this web page it is:
您可以使用 scipy.sparse.linalg 中的 lsqr 来求解具有最小二乘法的稀疏矩阵系统
You can use lsqr from scipy.sparse.linalg to solve sparse matrix systems with least squares