Compute the Jacobian matrix in Python

前端 未结 6 1741
温柔的废话
温柔的废话 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条回答
  •  猫巷女王i
    2021-02-02 01:55

    The Jacobian is only defined for vector-valued functions. You cannot work with arrays filled with constants to calculate the Jacobian; you must know the underlying function and its partial derivatives, or the numerical approximation of these. This is obvious when you consider that the (partial) derivative of a constant (with respect to something) is 0.

    In Python, you can work with symbolic math modules such as SymPy or SymEngine to calculate Jacobians of functions. Here's a simple demonstration of an example from Wikipedia:

    Using the SymEngine module:

    Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:40:30) [MSC v.1500 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    >>> import symengine
    >>>
    >>>
    >>> vars = symengine.symbols('x y') # Define x and y variables
    >>> f = symengine.sympify(['y*x**2', '5*x + sin(y)']) # Define function
    >>> J = symengine.zeros(len(f),len(vars)) # Initialise Jacobian matrix
    >>>
    >>> # Fill Jacobian matrix with entries
    ... for i, fi in enumerate(f):
    ...     for j, s in enumerate(vars):
    ...         J[i,j] = symengine.diff(fi, s)
    ...
    >>> print J
    [2*x*y, x**2]
    [5, cos(y)]
    >>>
    >>> print symengine.Matrix.det(J)
    2*x*y*cos(y) - 5*x**2
    

提交回复
热议问题