How to get the Gradient and Hessian | Sympy

Randerson picture Randerson · Sep 18, 2016 · Viewed 9.5k times · Source

Here is the situation: I have a symbolic function lamb which is function of the elements of the variable z and the functions elements of the variable h. Here is an image of the lamb symbolic function

enter image description here.

Now I would like the compute the Gradient and Hessian of this function with respect to the variables eta and xi. Of course I googled for it but I could not find a straight way for doing this. What I found is here, but as I said it does not seen to be the best approach for this situation. Any idea? Bellow, the source code. Thanks.

from sympy import Symbol, Matrix, Function, simplify

eta = Symbol('eta')
xi = Symbol('xi')

x = Matrix([[xi],[eta]])

h = [Function('h_'+str(i+1))(x[0],x[1]) for i in range(3)]
z = [Symbol('z_'+str(i+1)) for i in range(3)]

lamb = 0
for i in range(3):
    lamb += 1/(2*sigma**2)*(z[i]-h[i])**2
simplify(lamb)

Answer

Stelios picture Stelios · Sep 18, 2016

You can simply compute the gradient vector "manually" (assuming that the variables are ordered as (z1, z2, z3, eta)):

[lamb.diff(x) for x in z+[eta]]

Similarly, for the Hessian matrix:

[[lamb.diff(x).diff(y) for x in z+[eta]] for y in z+[eta]]