我如何在没有已知 objective 函数(比如一些随机函数)且具有已知变量和约束的情况下使用 gekko 优化器?
how can I use gekko optimizer without a known objective function(let say some random function) and with known variables and constraints?
我尝试使用连接到 A 的 gekko 最小化和最大化随机 'test function'。A 由范围 (0-100) 和 A < 100.However 之和之间的 4 个参数组成我不断得到奇怪的结果,因为测试函数的最小值应该是 2500,最大值应该是 10000。我的代码是 below.Can 谁能告诉我问题出在哪里?提前致谢
import numpy as np
from gekko import GEKKO
def test_function(x):
return np.dot(x, x)
A = m.Array(m.Var, (4))
# initial guess
ig = [1, 5, 5, 1]
# lower bounds
i = 0
for Ai in A:
Ai.value = ig[i]
Ai.lower = 0
Ai.upper = 100
i += 1
m.Equation(np.sum(A) < 100)
m.Obj(test_function(A))
m.solve()
print(test_function(A))
print (A)
结果
Solver : IPOPT (v3.12)
Solution time : 1.379999999971915E-002 sec
Objective : 4.141037033873033E-007
Successful solution
---------------------------------------------------
(((((v1)*(v1))+((v2)*(v2)))+((v3)*(v3)))+((v4)*(v4)))
[[0.00042734466188] [0.00015629584657] [0.00015629584657]
[0.00042734466188]]
Process finished with exit code 0
您定义下限和 objective 函数的方式,gekko 选择刚好高于 0 的小数。刚好高于零的小数满足您给定的所有界限,并且这就是 objective 如此之低的原因。此外,如果您将 objective 函数设置为负值,它会将其最大化至 5000。我不确定您从哪里获得了预期的最小值和最大值。
我修改了问题以符合您的陈述。还有一个列表推导式,它简化了定义具有上限和下限的新变量的过程。以下脚本显示了两种访问 test_function(x)
的方法,其中 (1) Gekko 变量是符号表达式,或 (2) 使用数值来评估该约束和 objective 函数。
import numpy as np
from gekko import GEKKO
m = GEKKO(remote=False)
def test_function(x):
return np.dot(x, x)
ig = [1, 5, 5, 1] # initial guess
A = np.array([m.Var(value=ig[i],lb=0,ub=10000,name='a'+str(i)) \
for i in range(4)])
m.Equation(test_function(A)>2500)
m.Equation(test_function(A)<10000)
m.Minimize(test_function(A))
m.solve()
# extract values to get a numerical solution of test_function
A_sol = [A[i].value[0] for i in range(4)]
print(test_function(A_sol))
# get the objective function value from the solver
print(m.options.OBJFCNVAL)
# print variables
print (A)
脚本的结果如下所示。如果您使用 print(test_function(A_sol))
,它会打印 Gekko 用来求解的符号表达式。在您的情况下,您可能对数值解感兴趣,而不是符号形式。
# results
2499.999999993099
2500.0
[[14.90599615] [32.059495922] [32.059495922] [14.90599615]]
m.options.OBJFCNVAL
和计算表达式给出相同的结果,但由于机器精度的原因略有不同。