1

我无法在scipy.optimize.minimize. 我创建了一个最小的问题来仔细检查,但我也无法让它工作。有人会碰巧知道问题是什么吗?

这是我的例子:

import numpy as np 
import jax.numpy as jnp 
import scipy

from scipy.optimize import minimize 
from scipy.optimize import NonlinearConstraint

from jax import grad, jit, vmap, jacrev, hessian
    
size_overall = 4 

constr_size= size_overall 

x0 = np.dot(2,np.ones((size_overall)))

def cost_func(x):    
    return jnp.dot(x,x)

def cost_func_grad(x):   
    return jnp.dot(2,x)

def test(x):     
    return x-np.ones(constr_size)

def jac_func(x):    
    return np.array(jacrev(test)(x0))

def hess_func(x,v): 
    temp = hessian(test)(x0)    

    temp0 = temp[0]     
    for i in range(0,constr_size):  
        temp0 = np.concatenate((temp0,temp[i])) 

    return temp0

print(hess_func(x0,0)) 
print(hess_func(x0,0).shape)


nonlinear_constraint = NonlinearConstraint(test,np.size(constr_size),np.size(constr_size),jac_func,hess_func)

res2 = minimize(cost_func, x0, method='trust-constr', jac=cost_func_grad,
            constraints=[nonlinear_constraint], options={'disp': True})
4

1 回答 1

0

请参阅我上面的评论以获取答案。

这似乎解决了这个问题:

def hess_func(x,v): 
    temp = hessian(test)(x0)    
    temp0 = v[0]*temp[0]
    for i in range(1,constr_size):
        temp0 = temp0 + v[i]*temp[i]
    return temp0

print(hess_func(x0,np.zeros((constr_size)))) 
print(hess_func(x0,np.zeros((constr_size))).shape)

我认为这可能是因为它想要的 Hessian 形状与 Hessian 本身的标准定义不同,而 H(x,v) 实际上是一个总和,请参阅:https ://docs.scipy.org/doc/scipy /reference/tutorial/optimize.html#constrained-minimization-of-multivariate-scalar-functions-minimize

于 2021-07-26T22:06:42.200 回答