返回Python numdifftools.Jacobian矩阵

时间:2015-04-17 13:30:54

标签: python matrix nonlinear-functions

我正在尝试编写将返回雅可比矩阵的Python代码。安装numdifftools并运行内置函数numdifftools.Jacobian()后,我得到了这个:

numdifftools.core.Jacobian object at 0x1032fe2d0

我在网上找到的所有示例都会为我返回此结果。是否有一个我失踪的命令,或者我错过了 - 解释这个功能是如何工作的?

# 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;
#=============================================

1 个答案:

答案 0 :(得分:0)

研究多个变量的多个输出函数的相同问题,我做了这个简单的例子,演示了numdifftools Jacobian函数的使用。

请注意使用numpy数组来定义多个输出而不是列表。

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]))

执行返回

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