Mathain
Mathain

Reputation: 31

Return Python numdifftools.Jacobian matrix

I am trying to write Python code that will return a Jacobian matrix. After installing numdifftools and running the in-built function numdifftools.Jacobian() I get this:

numdifftools.core.Jacobian object at 0x1032fe2d0

All examples I find online return this result for me. Is there a command I'm missing or am I miss-interpreting how this function works??

# To approximate a solution for a series of 
# overdeterministic, non-linear equations.
# Find the point of intersection

import scipy
import numpy as np
import numdifftools as nd 

# The matrix A, equations stored in rows in the form:
# [x^2, y^2, x, y]
def MatrixA():
return np.matrix([  [1, 1, 0, 0],
                    [1, 1, 4, -2],
                    [0, 0, 4, -2],
                    [4, 0, 22, -9],
                    [5, 0, 0, 1]
                    ])

# The matrix B, the answers of the equations in Matrix A
def MatrixB():
    return np.matrix([  [16],
                        [6],
                        [-13],
                        [31.5204],
                        [1.288]
                        ])


#Using the Moore-Penrose method to solve 
#an overdetermined set of equations
def MoorePenrose(A):
    Ans = A.getT() * A
    Ans = Ans.getI()
    Ans = Ans * A.getT()
    return Ans

# Linearise the equations by using the Newton method
# This will generate the best possible linear version
# of the nonlinear system.
def Linearise(A):
    return nd.Jacobian(A)

#=============================================
# Program Main() {
#=============================================

#Read in A matrix of equations
A = MatrixA()

#Read in B matrix of solutions (RHS of A Matrices equations)
B = MatrixB()

#Solution => 
#Linearise Matrix A
A = Linearise(A)
print A

#A = Moorse Penrose psuedoinverse of A
A = MoorePenrose(A)

#Unknowns Matrix X = A * B
A = A * B

# Print out the unknowns Matrix.
print A

#=============================================
# } Main End;
#=============================================

Upvotes: 3

Views: 3829

Answers (1)

RandomCoder
RandomCoder

Reputation: 7034

Investigating the same question for multiple output function of multiple variables, I made this simple example demonstrating the use of numdifftools Jacobian function.

Please note the use of numpy array to define function multiple outputs and not lists.

import numpy as np
import numdifftools as nd

# Define your function 
# Can be R^n -> R^n as long as you use numpy arrays as output
def f(x):
    return np.array([x[0],x[1]])

# Define your Jacobian function
f_jacob = nd.Jacobian(f)

# Use your Jacobian function at any point you want.
# In our case, for a R² -> R² function, it returns a 2x2 matrix with all partial derivatives of all outputs wrt all inputs
print(f_jacob([1,2]))

Execution returns

[[1. 0.]
 [0. 1.]]

Upvotes: 2

Related Questions