Scipy 的非线性函数约束优化

Constrained Optimization with Scipy for a nonlinear fucntion

我正在尝试最大化 x^(0.5)y^(0.5) st. x+y=10 使用 scipy.

我不知道该用什么方法。如果有人可以指导我,我将非常感激。

这里有两种可能的方法:

第一个版本使用fmin_cobyla,因此不需要f的导数。

from scipy.optimize import fmin_cobyla

f = lambda x : - (x[0]**0.5 * x[1]**(0.5))

# x + y = 10 <=> (x + y - 10 >= 0) & (-x -y + 10 >= 0)
c1 = lambda x: x[0] + x[1] - 10
c2 = lambda x: 10 - x[0] - x[1]

fmin_cobyla(f, [0,0], cons=(c1, c2))

我们得到:array([ 4.9999245, 5.0000755])

第二个版本使用fmin_slsqp并利用我们可以分析计算偏导数:

from scipy.optimize import fmin_slsqp

f = lambda x : - (x[0]**0.5 * x[1]**(0.5))

def f_prime(x):
    ddx1 = 0.5 * x[0]**-0.5 * x[1]**0.5
    ddx2 = 0.5 * x[1]**-0.5 * x[0]**0.5
    return [ddx1, ddx2]

f_eq = lambda x: x[0] + x[1] - 10

fmin_slsqp(f, [0.01,0.01], fprime=f_prime, f_eqcons=f_eq)

这是输出:

Optimization terminated successfully.    (Exit mode 0)
        Current function value: -5.0
        Iterations: 2
        Function evaluations: 2
        Gradient evaluations: 2