I have a function in Python:
def f(x):
return x[0]**3 + x[1]**2 + 7
# Actually more than this.
# No analytical expression
It's a scalar valued function of a vector.
How can I approximate the Jacobian and Hessian of this function in numpy or scipy numerically?
An approximation of the Hessian is obtained from the analytical formulation by partially solving first-order sensitivities to reduce computational time, while neglecting second-order sensitivities to ease implementation.
Thus, the Hessian matrix is the matrix with the second-order partial derivatives of a function. On the other hand, the matrix with the first-order partial derivatives of a function is the Jacobian matrix.
The Hessian is symmetric if the second partials are continuous. The Jacobian of a function f : n → m is the matrix of its first partial derivatives. Note that the Hessian of a function f : n → is the Jacobian of its gradient.
Calculating the Hessian matrix. The minimum is the point x=0, y=0. For a purely quadratic function like this one, the Newton-Raphson method finds the minimum in a single step from any point on the surface.
(Updated in late 2017 because there's been a lot of updates in this space.)
Your best bet is probably automatic differentiation. There are now many packages for this, because it's the standard approach in deep learning:
Another option is to approximate it with finite differences, basically just evaluating (f(x + eps) - f(x - eps)) / (2 * eps)
(but obviously with more effort put into it than that). This will probably be slower and less accurate than the other approaches, especially in moderately high dimensions, but is fully general and requires no code changes. numdifftools
seems to be the standard Python package for this.
You could also attempt to find fully symbolic derivatives with SymPy
, but this will be a relatively manual process.
Restricted to just SciPy, the most convenient way I found was scipy.misc.derivative, within the appropriate loops, with lambdas to curry the function of interest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With