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?
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
You can calculate the left inverse using matrix calculations:
(Why? Because:
)
Test:
Result:
You can use lsqr from scipy.sparse.linalg to solve sparse matrix systems with least squares
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.You can also look for the equivalent of the pseudo-inverse function
pinv
innumpy/scipy
, as an alternative to the other answers that is.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.