What's the equivalent to `solve` for `pinv`?

Viewed 55

A linear system A @ x = b can be solved in (at least) two ways:

  1. evaluate the inverse explicitly and apply it to b, i.e., x = np.linalg.inv(A) @ b.
  2. use x = np.linalg.solve(A, b).

The latter is usually preferred for both performance and numerical reasons. Is there an analogue to solve for the pseudoinverse pinv? In other words, I'm looking for a function psolve such that psolve(A, b) == np.linalg.pinv(A) @ b.

1 Answers

You can use numpy.linalg.lstsq or scipy.linalg.lstsq.

For example, in the following, x1 is computed using numpy.linalg.pinv, and x2 is computed using numpy.linalg.lstsq.

In [251]: A = np.arange(1, 10).reshape(3, 3)

In [252]: b = np.array([0, -1, 9])

In [253]: x1 = np.linalg.pinv(A) @ b

In [254]: x1
Out[254]: array([ 2.91666667,  0.5       , -1.91666667])

In [255]: x2, res, rnk, s = np.linalg.lstsq(A, b, rcond=None)

In [256]: x2
Out[256]: array([ 2.91666667,  0.5       , -1.91666667])
Related