Skip to main content
 首页 » 编程设计

python之如何在 scipy 优化(python 2.7)中定义变量之间的相互依赖关系

2025年05月04日8langtianya

我需要优化一个由多个元素组成的复杂函数,这些元素以 xi=1 和 0<=xi<=1 之和的方式相互依赖。

所以我使用 scipy optimize.minimize with bounds。

但我不知道如何指定 xi 的相互依赖性。我使用附加变量 (x100) 并将其边界设置为 (0, 0) 并在函数 x100=1-x1-x2-x3-x4-x5 中遵循条件。

不幸的是,结果无法正常工作。我需要更改 def arg 但我不知道如何更改

我如何指定 xi 之间的相互依赖性(以便 sum_x=1)?

from scipy.optimize import minimize 
from numpy import random, mean, var, std 
 
def arg(x1,x2,x3,x4,x5,x100): 
    x100=1-x1-x2-x3-x4-x5 
    r = mean(x1*x2*x3*x4*x5)*std(x1+x2-x3+x4-x5) 
    return r 
 
def new_arg(x): 
    return -arg(*x) 
 
 
fun = new_arg 
x0 = (0.5, 0.5, 0.5, 0.5, 0.5,\ 
    0.0) 
res = minimize(fun, x0, method='SLSQP', bounds = ((0, 1),(0, 1), (0, 1),\ 
                                             (0, 1),(0, 1),(0, 0))) 
kpi_opt = res.x 
sum_x=res.x[0]+res.x[1]+res.x[2]+res.x[3]+res.x[4] 
 
print 'kpi_opt',kpi_opt 
print 'sum of xi = ',sum_x 

请您参考如下方法:

在你的例子中,我认为你想进一步定义一个由 f_eqcons 参数约束的相等函数。它需要是一个可调用函数,并且在成功优化的问题中应该返回 0(或仅包含 0 的数组)。按照您的最小示例:

import scipy.optimize as ss 
def f(x): 
    x1, x2, x3, x4, x5=x 
    return -np.mean(x1*x2*x3*x4*x5)*np.std(x1+x2-x3+x4-x5) 
 
x0=(0.5, 0.5, 0.5, 0.5, 0.5) 
 
def eq_f(x): 
    x1, x2, x3, x4, x5=x 
    return sum(x) 
 
res=ss.fmin_slsqp(f, x0, f_eqcons=eq_f, bounds = ((0, 1),(0, 1), (0, 1),(0, 1),(0, 1))) 

结果:

Optimization terminated successfully.    (Exit mode 0) 
            Current function value: -0.0 
            Iterations: 1 
            Function evaluations: 8 
            Gradient evaluations: 1 
In [11]: 
 
res 
Out[11]: 
array([  0.00000000e+00,   5.55111512e-17,   0.00000000e+00, 
         0.00000000e+00,   0.00000000e+00])