约束优化

2024-10-03 15:25:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写一个约束优化器。我试图最小化函数sub,它接受变量rhoRho是需要满足约束0<;=rho<;=1.以下是我目前掌握的情况。我得到的错误'奇异矩阵C在LSQ子问题',这使我认为我没有正确定义我的约束函数。我只知道COBYLA支持不等式约束的方法,但我不知道如何以这种形式编写它。我用“eq”表示SLSQP方法。请帮帮我

def inequality(rho):
    return np.sum(np.logical_or((rho < 0), (rho > 1)))

cons = [{'type':'eq', 'fun': inequality}]

def opt2(sub):
    res2 = minimize(sub, rho(9), method='SLSQP', jac=gradient_ext, constraints=cons)
    return res2

optimize2 = opt2(subroutine_ext)
print(optimize2)

Tags: 方法函数ltreturndefnpexteq
1条回答
网友
1楼 · 发布于 2024-10-03 15:25:37

如果不知道函数sub及其雅可比矩阵,就很难提供正确的帮助,无论如何,在您的例子中不需要使用任何约束。为minimize提供变量边界就足够了。假设rho是numpy数组:

bnds = [(0,1) for _ in range(len(rho))]

def opt2(sub):
    res2 = minimize(sub, x0=your_starting_point, bounds=bnds, jac=gradient_ext)
    return res2

optimize2 = opt2(subroutine_ext)
print(optimize2)

相关问题 更多 >