【问题标题】:Scipy optimized function with dynamic conditions具有动态条件的 Scipy 优化函数
【发布时间】: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


【解决方案1】:

在循环中创建 lambda 表达式时需要捕获循环变量i,更多详细信息请参见here

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, i=i: x[Lorder[i]]-x[Lorder[i+1]]})

但是,还要注意

( -x[0] + x[1] ) >= 0
( -x[1] + x[2] ) >= 0

可以写成矩阵-向量积

        ( -1  1   0)   (x[0]) 
D @ x = ( 0  -1   1) @ (x[1]) >= 0
        ( 0   0   0)   (x[2])

因此您可以一次添加所有约束:

n = 3
D = np.zeros((n, n))
for i in range(len(Lorder)-1):
    k = Lorder[i]
    r = Lorder[i+1]
    D[-i+1, [k, r]] = [1.0, -1.0]

con = [{"type" : "ineq", "fun" : lambda x: fun_test(x)},
       {"type" : "ineq", "fun" : lambda x: D @ x}]

【讨论】:

    猜你喜欢
    • 2015-09-26
    • 1970-01-01
    • 2018-03-31
    • 2016-10-11
    • 2013-08-15
    • 1970-01-01
    • 2022-01-08
    • 2020-11-25
    • 1970-01-01
    相关资源
    最近更新 更多