我想计算 Gradient
和 Hessian
关于变量的以下函数 x
和 y
.有人可以帮忙吗?非常感谢。
我从 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]])
更新:
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
How to get the Gradient and Hessian | Sympy https://docs.sympy.org/dev/modules/vector/fields.html
最佳答案
表达式有 hessian
函数,矩阵有 jacobian
方法。
这里是你的问题的函数和变量:
>>> 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
方法:
>>> 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 - 在 Python 中定义梯度和 hessian 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60164477/