[英]TypeError: x must be a python list of GEKKO parameters, variables, or expressions
[英]GEKKO TypeError in python
認為:
# ww is a numpy array
ww.shape
>>>(10, 1)
# C is a numpy array
C.shape
>>>(5, 10)
我想用特定的目標 function 解決 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)
Output:
TypeError: must be real number, not GK_Operators
錯誤圖片:
我猜這個錯誤是特定目標函數的原因! 因為具有簡單的目標函數,例如:
m.Obj(x1 + x2)
我沒有收到錯誤。 所以我猜錯誤來自特定的目標函數。
我該如何解決這個錯誤? 問題出在哪里?
這應該適合你。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.