Time for action – computing the pseudo inverse of a matrix

Let's compute the pseudo inverse of a matrix:

  1. First, create a matrix:
    A = np.mat("4 11 14;8 7 -2")
    print("A
    ", A)

    The matrix we created looks like the following:

    A
    [[ 4 11 14]
     [ 8  7 -2]]
    
  2. Calculate the pseudo inverse matrix with the pinv() function:
    pseudoinv = np.linalg.pinv(A)
    print("Pseudo inverse
    ", pseudoinv)

    The pseudo inverse result is as follows:

    Pseudo inverse
    [[-0.00555556  0.07222222]
     [ 0.02222222  0.04444444]
     [ 0.05555556 -0.05555556]]
    
  3. Multiply the original and pseudo inverse matrices:
    print("Check", A * pseudoinv)

    What we get is not an identity matrix, but it comes close to it:

    Check [[  1.00000000e+00   0.00000000e+00]
     [  8.32667268e-17   1.00000000e+00]]
    

What just happened?

We computed the pseudo inverse of a matrix with the pinv() function of the numpy.linalg module. The check by matrix multiplication resulted in a matrix that is approximately an identity matrix (see pseudoinversion.py):

from __future__ import print_function
import numpy as np

A = np.mat("4 11 14;8 7 -2")
print("A
", A)

pseudoinv = np.linalg.pinv(A)
print("Pseudo inverse
", pseudoinv)

print("Check", A * pseudoinv)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset