首页 > 解决方案 > 寻找多维函数的Hessian矩阵

问题描述

我正在尝试创建 10 维凸函数。我知道它的 hessian 矩阵的特征值必须是正的,函数才能是凸的。我正在做下面的事情来找到 hessian 矩阵,但它的输入是一个数组,我不知道如何将函数表示为数组。

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)

标签: pythonpython-3.xnumpymathoptimization

解决方案


正如您从中获得此代码的问题x中所述,是参数空间中均匀间隔网格的节点处的函数值,而不是函数本身。

如果无法解析地计算函数的粗麻布,则必须使用此示例代码中的有限差分公式


推荐阅读