简体   繁体   English

为什么约束在 scipy.optimize.minimize 中失败

[英]Why do constraints fail in scipy.optimize.minimize

    def get_cons(self, ub, lb):
        cons = []
        for i in range(len(ub)):
            cons.append({'type':'ineq','fun':lambda x0:ub[i]-x0[i]})
            cons.append({'type':'ineq','fun':lambda x0:x0[i]-lb[i]})
        return cons
    ub = [1,3,1,1]
    lb = [0,0,0,0]
    cons = self.get_cons(self.ub, self.lb)
    res = minimize(fun, x0[:,i], method='SLSQP', constraints=cons)

Here fun is custom loss function initial parameter is [0.08024884 0.14003958 0.0786131 0.00157402].这里fun是自定义损失function初始参数是[0.08024884 0.14003958 0.0786131 0.00157402]。 I expect all parameter>0,but after optimize parmeter is [-0.45684621 0.02531972 -0.10755587 0.2108312].我希望所有参数> 0,但优化参数后是 [-0.45684621 0.02531972 -0.10755587 0.2108312]。

Whether this constraint fails?这个约束是否失效?

There's no need to use generic constraints for adding simple bounds on the variables.无需使用通用约束来为变量添加简单的界限。 Instead, pass the variable bounds via minimize's bound argument:相反,通过最小化的绑定参数传递变量边界:

bounds = [(l, u) for (l, u) in zip(lb, ub)]

res = minimize(fun, x0[:, i], bounds=bounds, method="SLSQP") 

However, if you really want to pass the bounds as generic constraints, you need to capture the value of the loop variable i :但是,如果您真的想将边界作为通用约束传递,则需要捕获循环变量i的值:

for i in range(len(ub)):
    cons.append({'type':'ineq','fun': lambda x0, i=i: ub[i]-x0[i]})
    cons.append({'type':'ineq','fun': lambda x0: i=i: x0[i]-lb[i]})
return cons

Otherwise, each constraint shares the value of i of the last loop iteration, see here for further details.否则,每个约束共享最后一次循环迭代的i值,有关详细信息,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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