我在python中有一个函数,如下所示:import numpy as np
def fun(Gp,Ra,Mr,Pot,Sp,Mc,Keep):
if(Keep==True):
return(Pot*np.tanh((Gp+Ra+Mr+ Mc)*Sp ))
假设以下数据:
^{2}$
我总共有100个GP,我想适当地分配它们
为了最大化objective_function:
在全部约束下,3个元素正
根据this的帖子,scipy.optimize将是一个好办法,但我很困惑如何把问题写下来
更新:我的尝试from scipy.optimize import minimize
y = {'A': {'RA': 0.5, 'MR': 0.97, 'POT': 0.25, 'SP': 0.25, 'MC': MC_1, 'keep': True},
'B': {'RA': 0.8, 'MR': 0.95, 'POT': 0.12, 'SP': 0.12, 'MC': MC_2, 'keep': True},
'C': {'RA': 0.9, 'MR': 0.99, 'POT': 0.05, 'SP': 0.15, 'MC': MC_3, 'keep': True}}
def objective_function(x):
return(
-(fun(x[0], Ra=y['A']['RA'], Mr=y['A']['MR'],
Pot=y['A']['POT'], Sp=y['A']['SP'],
Mc=y['A']['MC'], Keep=y['A']['keep']) +
fun(x[1], Ra=y['B']['RA'], Mr=y['B']['MR'],
Pot=y['B']['POT'], Sp=y['B']['SP'],
Mc=y['B']['MC'], Keep=y['B']['keep']) +
fun(x[2], Ra=y['C']['RA'], Mr=y['C']['MR'],
Pot=y['C']['POT'], Sp=y['C']['SP'],
Mc=y['C']['MC'], Keep=y['C']['keep']))
)
cons = ({'type': 'ineq', 'fun': lambda x: x[0] + x[1] + x[2] - 100})
bnds = ((0, None), (0, None), (0, None))
minimize(objective_function, x0=[1,1,1], args=y, method='SLSQP', bounds=bnds,
constraints=cons)
现在的问题是我得到错误ValueError: Objective function must return a scalar,而fun函数的输出是标量
更新2(在@Cleb comment之后)
现在我改变了函数:def objective_function(x,y):
temp = -(fun(x[0], Ra=y['A']['RA'], Mr=y['A']['MR'],
Pot=y['A']['POT'], Sp=y['A']['SP'],
Mc=y['A']['MC'], Keep=y['A']['keep']) +
fun(x[1], Ra=y['B']['RA'], Mr=y['B']['MR'],
Pot=y['B']['POT'], Sp=y['B']['SP'],
Mc=y['B']['MC'], Keep=y['B']['keep']) +
fun(x[2], Ra=y['C']['RA'], Mr=y['C']['MR'],
Pot=y['C']['POT'], Sp=y['C']['SP'],
Mc=y['C']['MC'], Keep=y['C']['keep']))
print("GP for the 1st: " + str(x[0]))
print("GP for the 2nd: " + str(x[1]))
print("GP for the 3rd: " + str(x[2]))
return(temp)
cons = ({'type': 'ineq', 'fun': lambda x: x[0] + x[1] + x[2] - 100})
bnds = ((0, None), (0, None), (0, None))
现在有两个问题:
1x[0],x[1],x[2]的值非常接近x[0],x[1],x[2]的和超过100