简体   繁体   English

在 Python 中定义梯度和 Hessian 函数

[英]Define gradient and hessian function in Python

I would like the compute the Gradient and Hessian of the following function with respect to the variables x and y .我想计算以下函数关于变量xyGradientHessian Anyone could help?任何人都可以帮忙吗? Thanks a lot.非常感谢。

在此处输入图片说明

I find a code relevant from github for calculation of Rosenbrock function.我从github 中找到了一个用于计算 Rosenbrock 函数的相关代码。

def objfun(x,y):
    return 10*(y-x**2)**2 + (1-x)**2
def gradient(x,y):
    return np.array([-40*x*y + 40*x**3 -2 + 2*x, 20*(y-x**2)])
def hessian(x,y):
    return np.array([[120*x*x - 40*y+2, -40*x],[-40*x, 20]])

Update:更新:

from sympy import symbols, hessian, Function, N

x, y = symbols('x y')
f = symbols('f', cls=Function)

f = (1/2)*np.power(x, 2) + 5*np.power(y, 2) + (2/3)*np.power((x-2), 4) + 8*np.power((y+1), 4)

H = hessian(f, [x, y]).subs([(x,1), (y,1)])
print(np.array(H))
print(N(H.condition_number()))

Ouput:输出:

[[9.00000000000000 0]
 [0 394]]
43.7777777777778

How to get the Gradient and Hessian | 如何获得梯度和Hessian | Sympy https://docs.sympy.org/dev/modules/vector/fields.html Sympy https://docs.sympy.org/dev/modules/vector/fields.html

There is the hessian function for expressions and the jacobian method for matrices.有用于表达式的hessian函数和用于矩阵的jacobian方法。

Here are the function and variables of your problem:以下是问题的函数和变量:

>>> from sympy.abc import x, y
>>> from sympy import ordered, Matrix, hessian
>>> eq = x**2/2 + 5*y**2 + 2*(x - 2)**4/3 + 8*(y + 1)**4
>>> v = list(ordered(eq.free_symbols)); v
[x, y]

We can write our own helper for gradient which will create a matrix and use the jacobian method on it:我们可以为梯度编写我们自己的助手,它将创建一个矩阵并在其上使用jacobian方法:

>>> gradient = lambda f, v: Matrix([f]).jacobian(v)

Then the quantities can be calculated as:那么数量可以计算为:

>>> gradient(eq, v)
Matrix([[x + 8*(x - 2)**3/3, 10*y + 32*(y + 1)**3]])
>>> hessian(eq, v)
Matrix([
[8*(x - 2)**2 + 1,                  0],
[               0, 96*(y + 1)**2 + 10]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM