在python

时间:2018-11-19 07:30:23

标签: python numpy optimization scipy data-science

有四个变量 (S1, S2, S3, S4) 有约束 (S1+S2+S3+S4=100)。 有四个给定的常量(C1, C2, C3, C4)。我想最大化(S1/C1 + S2/C2 + S3/C3 + S4/C4)的值。这是我在python中的代码:

#!/usr/bin/env python3

import numpy as np
from scipy.optimize import minimize

S0 = [25, 25, 25, 25]
C = [89415,8991,10944,15164]

def objective(S, C):
    total = 0
    for index in range(4):
        total = total + S[index]/C[index]        
    return -total

def constraint(S):
    return (100 - S[0] - S[1] - S[2] - S[3])

b = (0.0, 100.0)
boundaries = (b,b,b,b)
con = ({'type':'eq', 'fun':constraint})

solution = minimize(objective,S0,args=(C),method='SLSQP',bounds=boundaries,constraints=con)

print (solution)

我的代码只是返回S的初始猜测作为最终结果

fun: -0.0069931517268763755 jac: array([-1.11838453e-05, -1.11222384e-04, -9.13742697e-05, -6.59456709e-05]) message: 'Optimization terminated successfully.' nfev: 6 nit: 1 njev: 1 status: 0 success: True x: array([25., 25., 25., 25.])

我要去哪里错了?

1 个答案:

答案 0 :(得分:1)

函数输出值的差异似乎在优化器的默认容限内,以使优化器在迭代之间停止优化函数。将容差设置为较小的值,例如1e-12可以帮助:

solution = minimize(objective,S0,args=(C),method='SLSQP',bounds=boundaries,constraints=con, tol=1e-12)

结果:

   fun: -0.01112223334445557
     jac: array([ -1.11837871e-05,  -1.11222267e-04,  -9.13742697e-05,
        -6.59456709e-05])
 message: 'Optimization terminated successfully.'
    nfev: 192
     nit: 32
    njev: 32
  status: 0
 success: True
       x: array([  0.00000000e+00,   1.00000000e+02,   3.01980663e-14,
         0.00000000e+00])

大约等于绝对最大解[0,100,0,0]。