在Python中定义渐变和hessian函数 [英] Define gradient and hessian function in Python

查看:136
本文介绍了在Python中定义渐变和hessian函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望针对变量xy计算以下函数的GradientHessian.有人可以帮忙吗?非常感谢.

I would like the compute the Gradient and Hessian of the following function with respect to the variables x and y. Anyone could help? Thanks a lot.

我从 github 用于计算Rosenbrock函数.

I find a code relevant from github for calculation of Rosenbrock function.

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

更新:

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

输出:

[[9.00000000000000 0]
 [0 394]]
43.7777777777778

如何获取渐变和粗麻布| Sympy https://docs.sympy.org/dev/modules/vector/fields. html

推荐答案

对于表达式,有hessian函数,对于矩阵有jacobian方法.

There is the hessian function for expressions and the jacobian method for matrices.

这是您问题的函数和变量:

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]

我们可以编写自己的渐变帮助程序,以创建矩阵并在其上使用jacobian方法:

We can write our own helper for gradient which will create a matrix and use the jacobian method on it:

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

那么数量可以计算为:

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

这篇关于在Python中定义渐变和hessian函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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