Compute the Jacobian matrix in Python

前端 未结 6 1737
温柔的废话
温柔的废话 2021-02-02 01:24
import numpy as np


a = np.array([[1,2,3],
              [4,5,6],
              [7,8,9]])


b = np.array([[1,2,3]]).T

c = a.dot(b) #function

jacobian = a # as partial         


        
6条回答
  •  花落未央
    2021-02-02 01:48

    Here is a Python implementation of the mathematical Jacobian of a vector function f(x), which is assumed to return a 1-D numpy array.

    import numpy as np
    
    def J(f, x, dx=1e-8):
        n = len(x)
        func = f(x)
        jac = np.zeros((n, n))
        for j in range(n):  # through columns to allow for vector addition
            Dxj = (abs(x[j])*dx if x[j] != 0 else dx)
            x_plus = [(xi if k != j else xi + Dxj) for k, xi in enumerate(x)]
            jac[:, j] = (f(x_plus) - func)/Dxj
        return jac
    

    It is recommended to make dx ~ 10-8.

提交回复
热议问题