【发布时间】:2021-10-14 09:12:54
【问题描述】:
这是我目前正在运行的一段代码:
def fun_test(x):
return 3*x[0]**2 + x[1] + 4*x[2]
con = [{"type" : "ineq", "fun" : lambda x: fun_test(x)},
{"type" : "ineq", "fun" : lambda x: x[0]-x[1]},
{"type" : "ineq", "fun" : lambda x: x[1]-x[2]},]
res = minimize(fun_test, method='COBYLA', x0=[3, 3, 3], constraints=con)
print("Resulting factors:",res.x)
所以在这里,我在 x[0] >= x[1] 和 x[1] >= x[2] 的条件下优化 fun_test 的因子。到目前为止一切顺利,结果是:
Resulting factors: [ 0.84965894 -0.31342016 -0.46308519]
现在,我的目标是能够动态设置最后两个条件,例如确定 x[2] >= x[1] 和 x[1] >= x[0],并列出说明每个因素相对于其他因素的优势。例如,列表 [2, 1, 0] 表示 x[2]>=x[1] 和 x[1]>=x[0]。
我现在正在做的是:
def fun_test(x):
return 3*x[0]**2 + x[1] + 4*x[2]
Lorder = [2,1,0]
con = [{"type" : "ineq", "fun" : lambda x: fun_test(x)}]
for i in range(np.shape(Lorder)[0]-1):
con.append({"type" : "ineq", "fun" : lambda x: x[Lorder[i]]-x[Lorder[i+1]]})
res = minimize(fun_test, method='COBYLA', x0=[3, 3, 3], constraints=con)
print("Resulting factors:",res.x)
但它不起作用,它给了我这个结果:
Resulting factors: [-0.22910497 2.05130651 -0.55219344]
您知道它为什么不起作用以及如何使它起作用吗?
【问题讨论】:
-
我编辑了我的答案并添加了更多细节。
标签: python optimization scipy