用Python计算雅可比矩阵 [英] Compute the Jacobian matrix in Python

查看:1684
本文介绍了用Python计算雅可比矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 derivative of c w.r.t to b is a.

我正在阅读有关jacobian Matrix的文章,试图构建一个,从到目前为止的内容来看,此python代码应被视为jacobian.我了解这个权利吗?

I am reading about jacobian Matrix, trying to build one and from what I have read so far, this python code should be considered as jacobian. Am I understanding this right?

推荐答案

您可以使用哈佛autograd库( link ),其中gradjacobian以函数作为参数:

You can use the Harvard autograd library (link), where grad and jacobian take a function as their argument:

import autograd.numpy as np
from autograd import grad, jacobian

x = np.array([5,3], dtype=float)

def cost(x):
    return x[0]**2 / x[1] - np.log(x[1])

gradient_cost = grad(cost)
jacobian_cost = jacobian(cost)

gradient_cost(x)
jacobian_cost(np.array([x,x,x]))

否则,您可以使用sympy中可用于矩阵的jacobian方法:

Otherwise, you could use the jacobian method available for matrices in sympy:

from sympy import sin, cos, Matrix
from sympy.abc import rho, phi

X = Matrix([rho*cos(phi), rho*sin(phi), rho**2])
Y = Matrix([rho, phi])

X.jacobian(Y)

此外,您可能还希望看到此低级变体(此处提供了很好的文档.

Also, you may also be interested to see this low-level variant (link). MATLAB provides nice documentation on its jacobian function here.

这篇关于用Python计算雅可比矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆