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)
参数定义如下:
fun: callable
: 最小化的目标函数,定义为fun(x, *args) -> float
。x
是形状为$(n,)$的一维数组,用于存放变量;args
是一个元组,用于简化函数。x0: ndarray, shape (n,)
: 变量的初始值。args: tuple, optional
: 传递给目标函数及其导数的额外参数。method: str or callable, optional
: 求解方法,默认为BFGS,可选L-BFGS-B,SLSQP,Nelder-Mead,Powell,CG,Newton-CG,TNC,COBYLA,dogleg,trust-constr,trust-ncg,trust-exact,trust-krylov,。jac: {callable, ‘2-point’, ‘3-point’, ‘cs’, bool}, optional
:计算梯度向量的方法,仅在BFGS,CG,Newton-CG,L-BFGS-B,SLSQP,TNC,dogleg,trust-constr,trust-ncg,trust-exact,trust-krylov中使用。hess: {callable, ‘2-point’, ‘3-point’, ‘cs’, HessianUpdateStrategy}, optional
:计算Hessian矩阵的方法,仅在Newton-CG,dogleg,trust-constr,trust-ncg,trust-exact,trust-krylov中使用。hessp: callable, optional
:目标函数的Hessian矩阵乘以一个随机向量$p$,仅在Newton-CG,trust-constr,trust-ncg,trust-exact中使用。hess
与hessp
只需设定一个。bounds: sequence or Bounds, optional
:变量的边界,仅在Nelder-Mead,L-BFGS-B,SLSQP,TNC,Powell,trust-constr中使用。以$(min,max)$对的形式定义每个变量的边界。如果没有边界,则用$None$标识。constraints: {Constraint, dict} or List of {Constraint, dict}, optional
:约束条件,仅在SLSQP,COBYLA,trust-constr中使用。约束以字典的形式给出,其键包括:typr: str
:约束类型。eq
等于$0$,ineq
大于等于$0$。fun: callable
:约束函数jac: callable, optional
:约束函数的Jacobian,仅对SLSQP。
tol: float, optional
:误差的容忍程度,精度超过该值则迭代停止。options: dict, optional
:通用设置,包括:maxiter: int
:最大迭代次数disp: bool
:是否打印迭代过程
例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]