简体   繁体   English

如何用 Python Gekko 解决绝对值 abs() 目标?

[英]How to solve Absolute Value abs() objective with Python Gekko?

An optimization problem with a squared objective solves successfully with IPOPT in Python Gekko.在 Python Gekko 中使用 IPOPT 成功解决了一个平方目标的优化问题。

from gekko import GEKKO
import numpy as np
m = GEKKO()
x = m.Var(); y = m.Param(3.2)
m.Obj((x-y)**2)
m.solve()
print(x.value[0],y.value[0])

However, when I switch to an absolute value objective np.abs(xy) (the numpy version of abs ) or m.abs(xy) (the Gekko version of abs ), the IPOPT solver reports a failed solution.但是,当我切换到绝对值目标np.abs(xy)abs的 numpy 版本)或m.abs(xy)abs的 Gekko 版本)时,IPOPT 求解器报告失败的解决方案。 An absolute value approximation m.sqrt((xy)**2) also fails.绝对值近似m.sqrt((xy)**2)也失败。

Failed Solution失败的解决方案

from gekko import GEKKO
import numpy as np
m = GEKKO()
x = m.Var(); y = m.Param(3.2)
m.Obj(m.abs(x-y))
m.solve()
print(x.value[0],y.value[0])

I understand that gradient-based solvers don't like functions without continuous first and second derivatives so I suspect that this is happening with abs() where 0 is a point that does not have continuous derivatives.我知道基于梯度的求解器不喜欢没有连续一阶和二阶导数的函数,所以我怀疑这发生在abs()中,其中0是没有连续导数的点。 Is there any alternative to abs() to reliably solve an absolute value with gradient-based solvers in Python Gekko?在 Python Gekko 中,是否有任何替代abs()可以可靠地使用基于梯度的求解器求解绝对值?

You can use m.abs2 instead, It takes into account the issue with the derivative and should solve the issue.您可以改用 m.abs2,它考虑了导数的问题,应该可以解决问题。

Here is one possible solution using gekko's binary switch variable:这是使用 gekko 的二进制开关变量的一种可能的解决方案:

from gekko import GEKKO
import numpy as np
m = GEKKO()
y = m.Param(3.2)
x = m.Var()
#intermediate
difference = m.Intermediate(x - y)

f = m.if3(difference, -difference, difference)

m.Obj(f)
m.solve()
print(x.value[0],y.value[0])

Returns: 3.2 3.2回报:3.2 3.2

m.if3(condition, x1, x2) takes value as a condition, and returns x1 if condition >= 0 or x1 if condition < 0 . m.if3(condition, x1, x2)将 value 作为条件,如果condition >= 0则返回x1 ,如果condition < 0则返回x1

There are various functions to get around this problem in the logical functions section of the documentation, including m.abs2 , m.abs3 , and m.if2 .在文档的逻辑函数部分有多种函数可以解决这个问题,包括m.abs2m.abs3m.if2

The type 2 functions use MPCC to solve and will continue using IPOPT.类型 2 函数使用 MPCC 求解并将继续使用 IPOPT。 The type 3 functions will change to APOPT automatically.类型 3 功能将自动更改为 APPT。

https://github.com/BYU-PRISM/GEKKO/blob/master/docs/model_methods.rst https://gekko.readthedocs.io/en/latest/model_methods.html#logical-functions https://github.com/BYU-PRISM/GEKKO/blob/master/docs/model_methods.rst https://gekko.readthedocs.io/en/latest/model_methods.html#logical-functions

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

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