我正在尝试创建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)发布于 2021-11-08 17:08:47
正如您从中获得此代码的question中所述,x是参数空间中等间距网格的节点处的函数值,而不是函数本身。
如果无法解析地计算函数的hessian,则必须使用finite difference formulas,如本示例代码中所示。
https://stackoverflow.com/questions/69872765
复制相似问题