简体   繁体   中英

Finding Hessian matrix of multi dimensional function

I am trying to create 10 dimensional convex function. I know that eigen values of its hessian matrix must be positive for function to be convex. I am doing the things below to find the hessian matrix, but its input is an array, I dont know how to represent a function as array.

def hessian(x):
    """
    Calculate the hessian matrix with finite differences
    Parameters:
       - x : ndarray
    Returns:
       an array of shape (x.dim, x.ndim) + x.shape
       where the array[i, j, ...] corresponds to the second derivative x_ij
    """
    x_grad = np.gradient(x) 
    hessian = np.empty((x.ndim, x.ndim) + x.shape, dtype=x.dtype) 
    for k, grad_k in enumerate(x_grad):
        # iterate over dimensions
        # apply gradient again to every component of the first derivative.
        tmp_grad = np.gradient(grad_k) 
        for l, grad_kl in enumerate(tmp_grad):
            hessian[k, l, :, :] = grad_kl
    return hessian

x = np.random.randn(100,100)
t=hessian(x)

As stated in the question you got this code from, x is the value of the function at the nodes of an evenly spaced mesh in parameter space, not the function itself.

If it's not possible to calculate the hessian of your function analytically, you have to use finite difference formulas like in this example code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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