0

我打算计算目标函数的最大值。我的编码如下。

import numpy as np
from scipy.optimize import minimize

# this is my objective function
def objective(x,sign=-1.0):
    x1=x[0]
    x2=x[1]
    x3=x[2]
    x4=x[3]
    x5=x[4]
    x6=x[5]
    return sign*(sum(x1+x2+x3+x4+x5+x6)) # to get maximum by using '-1' sign

def constraint1(x):
    return 5900-(x[0]+x[1]+0.949*x[2]+0.933*x[3]+0.824*x[4]+0.519*x[5])
def constraint2(x):
    return 6000-(x[2]+x[3]+0.922*x[4]+0.619*x[5])
def constraint3(x):
    return 6450-(x[3]+0.969*x[4]+0.777*x[5])

b1=(0,600)
b2=(0,475)
b3=(0,450)
b4=(0,500)
b5=(0,825)
b6=(0,6800)
bnds=(b1,b2,b3,b4,b5,b6)
cons=[constraint1,constraint2,constraint3]

solution=minimize(objective,x0=None,method='Nelder-Mead', tol=1e-6,
              bounds=bnds,constraints=cons)

但我得到了错误:

Traceback (most recent call last):
IndexError: index 1 is out of bounds for axis 0 with size 1

我应该怎么办??? 太感谢了。

4

1 回答 1

0

脚本的几个问题:在定义目标时 -

 return sign*(sum(x1+x2+x3+x4+x5+x6))

不能同时使用 sum 函数和“+”号。

在定义约束中:除了约束函数之外,还需要定义约束类型。约束函数:

   def constraint1(x):
        return 5900-(x[0]+x[1]+0.949*x[2]+0.933*x[3]+0.824*x[4]+0.519*x[5])
    def constraint2(x):
        return 6000-(x[2]+x[3]+0.922*x[4]+0.619*x[5])
    def constraint3(x):
        return 6450-(x[3]+0.969*x[4]+0.777*x[5]) 

约束类型(缺失):(假设所有 3 个约束都是不等式)

cons1 = {'type': 'ineq', 'fun': constraint1}
cons2 = {'type': 'ineq', 'fun': constraint2}
cons3 = {'type': 'ineq', 'fun': constraint3}
cons=[cons1,cons2,cons3]

上面将您的约束定义为

5900-(x[0]+x[1]+0.949*x[2]+0.933*x[3]+0.824*x[4]+0.519*x[5]) >= 0

最终代码有一些小的改进:

import numpy as np
from scipy.optimize import minimize

# this is my objective function
def objective(x, sign = -1.0):
    x1=x[0]
    x2=x[1]
    x3=x[2]
    x4=x[3]
    x5=x[4]
    x6=x[5]
    return sign*sum((x1,x2,x3,x4,x5,x6)) # to get maximum by using '-1' sign


def constraint1(x):
    return 5900-(x[0]+x[1]+0.949*x[2]+0.933*x[3]+0.824*x[4]+0.519*x[5])
def constraint2(x):
    return 6000-(x[2]+x[3]+0.922*x[4]+0.619*x[5])
def constraint3(x):
    return 6450-(x[3]+0.969*x[4]+0.777*x[5])

b1=(0,600)
b2=(0,475)
b3=(0,450)
b4=(0,500)
b5=(0,825)
b6=(0,6800)
bnds=(b1,b2,b3,b4,b5,b6)

cons1 = {'type': 'ineq', 'fun': constraint1}
cons2 = {'type': 'ineq', 'fun': constraint2}
cons3 = {'type': 'ineq', 'fun': constraint3}

cons=[cons1,cons2,cons3]

x0=[1,1,1,1,1,1]

result =minimize(objective,x0, method='SLSQP',bounds=bnds,constraints=cons,options={'maxiter': 10000, 'maxfev': None, 'disp': True, 'adaptive': True})
if result.success:
    fitted_x = result.x
    print(fitted_x)
else:
    raise ValueError(result.message)

结果:

Optimization terminated successfully.    (Exit mode 0)
            Current function value: -9363.537325000863
            Iterations: 32
            Function evaluations: 248
            Gradient evaluations: 31
    [ 503.10524364  418.45708136  450.          366.975       825.
     6800.        ]
于 2020-04-10T16:11:37.753 回答