python 中的 GEKKO 类型错误

GEKKO TypeError in python

假设:

# ww is a numpy array
ww.shape
>>>(10, 1)

# C is a numpy array
C.shape
>>>(5, 10)

我想用特定的 objective 函数解决 python 中的优化问题。
这是我为此目的编写的代码:

from gekko import GEKKO

m = GEKKO()
x1 = m.Var(value=0.2, lb=0, ub=1, integer=False) #float variable. Lower bound = 0, Upper Bound = 1, inirial Value = 0.2
x2 = m.Var(value=0.2, lb=0, ub=1, integer=False) #float variable. Lower bound = 0, Upper Bound = 1, inirial Value = 0.2
x3 = m.Var(value=0.2, lb=0, ub=1, integer=False) #float variable. Lower bound = 0, Upper Bound = 1, inirial Value = 0.2
x4 = m.Var(value=0.2, lb=0, ub=1, integer=False) #float variable. Lower bound = 0, Upper Bound = 1, inirial Value = 0.2
x5 = m.Var(value=0.2, lb=0, ub=1, integer=False) #float variable. Lower bound = 0, Upper Bound = 1, inirial Value = 0.2

x = [x1, x2, x3, x4, x5]

# My subjective function
m.Equation(x1 + x2 + x3 + x4 + x5 == 1)

# My specific Objective Function
## Remember that I specified about ww and C arrays right upside of these Codes
def Objective(x):
    i = 0
    j = 0
    C_b = np.zeros((1,C.shape[1])) # so C_b.shape would be (1, 10)
    
    for i in range(C.shape[1]):
        for j in range(5):
            C_b[0][i] += math.log10(x[j] * C[j,i])
    
    
    return -sum((C_b * ww)[0])


m.Obj(Objective(x))
m.solve(disp=False)

print(x1.value, x2.value, x3.value, x4.value, x5.value)

输出:

TypeError: must be real number, not GK_Operators

错误图片:

我猜这个错误是特定 objective 函数的原因! 因为 具有简单的 objective 功能,例如:

m.Obj(x1 + x2)

我没有收到错误!所以我猜错误来自特定的 objective 函数。

我该如何解决这个错误? 问题出在哪里?

这应该适合你。

from gekko import GEKKO
import numpy as np

nd = 5; md = 10
ww = np.random.rand(md)
C  = np.random.rand(nd,md)

m = GEKKO()
x = m.Array(m.Var,nd,value=1/nd,lb=0,ub=1)
m.Equation(sum(x)==1)
for i in range(C.shape[1]):
    for j in range(C.shape[0]):
        m.Maximize(ww[i]*(m.log10(x[j]*C[j,i])))
m.solve(disp=True)
for i,xi in enumerate(x):
    print(i+1,xi.value)

解总是1/nd,也与最初的猜测相同。您可以通过将初始猜测设置为 1.

之类的内容来检查求解器是否收敛到此最优解(而不仅仅是停留在初始猜测处)

通过更改 ww 的形状修复了错误。
解决问题之前:

ww.shape
>>>(10, 1)

修复了 :

的问题
ww.shape
>>>(10, )

现在提出的算法可以正常工作,没有任何错误或问题。这意味着它是 ww 形状的原因!在我将 ww 的形状更改为 (10, ) 而不是 (10, 1) 后它修复了。

现在假设:

# ww is a numpy array
ww.shape
>>>(10, )

# C is a numpy array
C.shape
>>>(5, 10)

更正和建议的算法:

from gekko import GEKKO
import numpy as np

nd = 5

m = GEKKO()
x = m.Array(m.Var,nd,value=1/nd,lb=0,ub=1)
m.Equation(sum(x)==1)

i = 0
j = 0
for i in range(C.shape[1]):
    for j in range(C.shape[0]):
        m.Maximize(ww[i]*(m.log10(x[j] *C[j,i])))
        
m.solve(disp=True)
for i,xi in enumerate(x):
    print(i+1,xi.value)