scipy.optimize.minimize.

scipy.optimize.minimize用于求解非线性规划问题,将问题表述为若干个变量的标量函数的最小值,其函数接口定义如下:

scipy.optimize.minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)

参数定义如下:

例1

\[\min \quad x+\frac{1}{x}\]
from scipy.optimize import minimize
import numpy as np

fun = lambda x: x+1/x
x0 = np.array([2])
res = minimize(fun, x0, method='SLSQP')
print(res.fun) # [2.00000008]

例2

\[\min \quad \frac{2+x}{1+y}-3x+4z \\ \text{s.t.} \quad 0.1≤x,y,z≤0.9\]
from scipy.optimize import minimize
import numpy as np

fun = lambda x: (2+x[0])/(1+x[1])-3*x[0]+4*x[2]
x0 = np.array([0.5,0.5,0.5])

cons = [{'type':'ineq', 'fun':lambda x:x[0]-0.1},
        {'type':'ineq', 'fun':lambda x:-x[0]+0.9},
        {'type':'ineq', 'fun':lambda x:x[1]-0.1},
        {'type':'ineq', 'fun':lambda x:-x[1]+0.9},
        {'type':'ineq', 'fun':lambda x:x[2]-0.1},
        {'type':'ineq', 'fun':lambda x:-x[2]+0.9}]

res = minimize(fun, x0, method='SLSQP', constraints=cons)
print(res.fun) # -0.773684210526435
print(res.x) # [0.9 0.9 0.1]

例3

\[\min \quad \log_2(1+\frac{2x}{3})+\log_2(1+\frac{3y}{4}) \\ \text{s.t.} \quad \log_2(1+\frac{2x}{5}) ≥ 5 \\ \quad \quad \log_2(1+\frac{3y}{2}) ≥ 5\]
from scipy.optimize import minimize
import numpy as np

fun = lambda x: np.log2(1+x[0]*2/3)+np.log2(1+x[1]*3/4)
x0 = np.array([0.5,0.5])

cons = [{'type':'ineq', 'fun':lambda x:np.log2(1+x[0]*2/5)-5},
        {'type':'ineq', 'fun':lambda x:np.log2(1+x[1]*3/2)-5}]

res = minimize(fun, x0, method='SLSQP', constraints=cons)
print(res.fun) # 9.763212360886708
print(res.x) # [77.5        20.66666658]