Book Image

NumPy: Beginner's Guide

By : Ivan Idris
Book Image

NumPy: Beginner's Guide

By: Ivan Idris

Overview of this book

Table of Contents (21 chapters)
NumPy Beginner's Guide Third Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
NumPy Functions' References
Index

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\n", 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\n", 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...