Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left inverse in numpy or 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?

like image 472
D R Avatar asked Feb 12 '10 08:02

D R


People also ask

How do you do inverse in Numpy?

We use numpy. linalg. inv() function to calculate the inverse of a matrix. The inverse of a matrix is such that if it is multiplied by the original matrix, it results in identity matrix.

How do you find the inverse in Python?

Python provides a very easy method to calculate the inverse of a matrix. The function numpy. linalg. inv() which is available in the python NumPy module is used to compute the inverse of a matrix.

How do you find the pseudo-inverse of a matrix in Numpy?

Compute the (Moore-Penrose) pseudo-inverse of a Hermitian matrix. The pseudo-inverse of a matrix A, denoted , is defined as: “the matrix that 'solves' [the least-squares problem] A x = b ,” i.e., if is said solution, then is that matrix such that x ¯ = A + b .

How do you find the pseudo-inverse in Python?

To Compute the (Moore-Penrose) pseudo-inverse of a matrix, use the numpy. linalg. pinv() method in Python. Calculate the generalized inverse of a matrix using its singular-value decomposition (SVD) and including all large singular values.


2 Answers

Use linalg.lstsq(A,y) since A is not square. See here for details. You can use linalg.solve(A,y) if A is square, but not in your case.

like image 63
Ramashalanka Avatar answered Oct 08 '22 15:10

Ramashalanka


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

from numpy import *
from scipy.sparse import csr_matrix
from scipy.optimize import leastsq
from numpy.random import rand

A=csr_matrix([[0.,1.],[0.,1.],[1.,0.]])
b=array([[2.],[2.],[1.]])

def myfunc(x):
    x.shape = (2,1)
    return (A*x - b)[:,0]

print leastsq(myfunc,rand(2))[0]

generates

[ 1.  2.]

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.

like image 33
Justin Peel Avatar answered Oct 08 '22 14:10

Justin Peel