十四.Optimize模块
1.优化(Optimization)
(1)标量函数优化(Scalar Functions Optimization):
求单变量标量函数的最小值:[<res>=]scipy.optimize.minimize_scalar(<fun>[,bracket=None,bounds=None,args=(),method='brent',tol=None,options=None])
#参数说明:
fun:指定函数;为callable
bracket:指定???;为sequence
bounds:指定变量范围;为(<low_bound>,<up_bound>)
#仅当method="Bounded"时有效,也仅当此时有格式要求
args:指定传入目标函数(<fun>)的其他参数;为tuple
method:指定优化方法;为"Brent"(Brent's algorithm)/"Bounded"(有约束最小化)/"Golden"(golden section search technique)/callable
tol:指定终止误差;为float
#误差小于此值时终止
options:指定其他参数;为dict
maxiter:指定最大迭代次数;为int
disp:指定???;为bool
res:返回优化结果;为OptimizeResult
(2)局部优化(Local Optimization):
求标量函数的最小值:[<res>=]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>为1×N array
x0:指定初始解;为1×N ndarray
args:指定传入目标函数(<fun>)的其他参数;为tuple
method:指定优化方法;为"Nelder-Mead"/"Powell"/"CG"/"BFGS"/"Newton-CG"/"L-BFGS-B"/"TNC"/"COBYLA"/"SLSQP"/"trust-constr"/"dogleg"/"trust-ncg"/"trust-exact"/"trust-krylov"/callable
jac:指定求梯度的方法;为callable/"2-point"/"3-point"/"cs"/bool
hess:指定求海塞矩阵的方法;为callable/"2-point"/"3-point"/"cs"/HessianUpdateStrategy
hessp:指定???;为callable
bounds:指定变量范围;为sequence/scipy.optimize.Bounds
constraints:指定变量约束;为<Constraint>/<Constraint> list/dict/dict list,其中<Constraint>为scipy.optimize.LinearConstraint/scipy.optimize.NonlinearConstraint
tol:指定终止误差;为float
#误差小于此值时终止
callback:指定每次迭代结束后调用的回调函数;为callable
options:指定其他参数;为dict
res:返回优化结果;为OptimizeResult
(3)全局优化(Global Optimization):
使用"盆地跳跃算法"(Basin-Hopping Algorithm)求函数的全局最小值:[<res>=]scipy.optimize.basinhopping(<fun>,<x0>[,niter=100,T=1.0,stepsize=0.5,minimizer_kwargs=None,take_step=None,accept_test=None,callback=None,interval=50,disp=False,niter_success=None,seed=None])
使用"暴力破解"(Brute Force)求函数在给定范围内的最小值:[<x0>,<fval>,<grid>,<Jout>=]scipy.optimize.brute(<func>,<ranges>[,args=(),Ns=20,full_output=0,finish=<function fmin at 0x7f215438a830>,disp=False,workers=1])
使用"差分进化算法"(Differential Evolution)求函数的全局最小值:[<res>=]scipy.optimize.differential_evolution(<func>,<bounds>[,args=(),strategy='best1bin',maxiter=1000,popsize=15,tol=0.01,mutation=(0.5,1),recombination=0.7,seed=None,callback=None,disp=False,polish=True,init='latinhypercube',atol=0,updating='immediate',workers=1,constraints=()])
使用"SHG Optimization"求函数的全局最小值:[<res>=]scipy.optimize.shgo(<func>,<bounds>[,args=(),constraints=None,n=100,iters=1,callback=None,minimizer_kwargs=None,options=None,sampling_method='simplicial'])
使用"双重退火算法"(Dual Annealing)求函数的全局最小值:[<res>=]scipy.optimize.dual_annealing(<func>,<bounds>[,args=(),maxiter=1000,local_search_options={
},initial_temp=5230.0,restart_temp_ratio=2e-05,visit=2.62,accept=-5.0,maxfun=10000000.0,seed=None,no_local_search=False,callback=None,x0=None])
2.最小二乘法与曲线拟合
(1)非线性最小二乘法(Nonlinear Least-Squares):
求解非线性最小二乘问题:[<result>=]scipy.optimize.least_squares(<fun>,<x0>[,jac='2-point',bounds=(-inf,inf),method='trf',ftol=1e-08,xtol=1e-08,gtol=1e-08,x_scale=1.0,loss='linear',f_scale=1.0,diff_step=None,tr_solver=None,tr_options={
},jac_sparsity=None,max_nfev=None,verbose=0,args=(),kwargs={
}])
(2)线性最小二乘法(Linear Least-Squares):
求解线性最小二乘问题:[<result>=]scipy.optimize.lsq_linear(<A>,<b>[,bounds=(-inf,inf),method='trf',tol=1e-10,lsq_solver=None,lsmr_tol=None,max_iter=None,verbose=0])
#min 0.5*||Ax-b||**2
#subject to lb<=x<=ub
#参数说明:
A:指定系数矩阵;为M×N array-like/M×N scipy.sparse.linalgLinearOperator sparse matrix
b:指定常数项;为1×M array-like
bounds:指定变量范围;为(<lb>,<ub>),元素均为float/array-like
method:指定优化方法;为"trf"/"bvls"
tol:指定相对终止变化;为float
#根的变化小于此值时终止
lsq_solver:指定求解无约束最小二乘问题的方法;None/"exact"/"lsmr"
lsmr_tol:指定scipy.sparse.linalg.lsmr()的终止误差;为None/float/"auto"
maxiter:指定最大迭代次数;为int
verbose:指定工作模式;为0(work silently)/1(display a termination report)/2(display progress during iterations)
result:返回结果;为OptimizeResult
######################################################################################################################
求解非负线性最小二乘问题:[<x>,<rnorm>=]scipy.optimize.nnls(<A>,<b>[,maxiter=None])
#argmin_x ||Ax-b||_2 for x>=0
#参数说明:
A:指定系数矩阵;为ndarray
b:指定常数项;为ndarray
maxiter:指定最大迭代次数;为int
x:返回解;为ndarray
rnorm:返回残差(||Ax-b||_2);为float
(3)曲线拟合(Curve Fitting):
使用最小二乘法进行曲线拟合:[<popt>,<pcov>=]scipy.optimize.curve_fit(<f>,<xdata>,<ydata>[,p0=None,sigma=None,absolute_sigma=False,check_finite=True,bounds=(-inf,inf),method=None,jac=None,**kwargs])
#参数说明:
f:指定"模型函数"(Model Function);为callable
xdata,ydata:指定自变量/因变量;均为array-like
p0:指定初始解;为array-like
sigma:指定<ydata>的不确定性;为None/MxM array-like/1xM array-like
absolute_sigma:指定<sigma>是否为绝对误差;为bool
check_finite:指定是否检查输入中是否包含Inf;为bool
bounds:指定变量范围;为(<lb>,<ub>),元素均为float/array-like
method:指定优化方法;为"lm"/"trf"/"dogbox"
jac:指定如何求雅可比矩阵;为callable/string/None
popt:返回参数值;为1×N ndarray
pcov:返回<popt>的协方差的估计值;为2-D ndarray
3.寻根(Root Finding)
(1)标量函数寻根:
求解标量函数的根:[<sol>=]scipy.optimize.root_scalar(<f>[,args=(),method=None,bracket=None,fprime=None,fprime2=None,x0=None,x1=None,xtol=None,rtol=None,maxiter=None,options=None])
#参数说明:
f:指定函数;为callable
args:指定要传给<f>的其他参数;为tuple
method:指定求解方法;为"bisect"/"brentq"/"brenth"/"ridder"/"toms748"/"newton"/"secant"/"halley"
bracket:指定变量范围;为(float,float)
fprime,fprime2:均用于告知<f>的返回值(详情参见官方文档);均为bool/callable
x0,x1:分别指定初始值/第2次尝试的值;均为float
xtol,rtol:分别指定绝对/相对终止误差;均为float
#误差小于此值时终止
maxiter:指定最大迭代次数;为int
options:指定其他参数;为dict
sol:返回函数的根;为RootResults
######################################################################################################################
使用"布伦特方法"(Brent's Method)求解标量函数的根:[<x0>,<r>=]scipy.optimize.brentq(<f>,<a>,<b>[,args=(),xtol=2e-12,rtol=8.881784197001252e-16,maxiter=100,full_output=False,disp=True])
使用带有"双曲线外推"(Hyperbolic Extrapolation)的布伦特方法求解标量函数的根:[<x0>,<r>=]scipy.optimize.brenth(<f>,<a>,<b>[,args=(),xtol=2e-12,rtol=8.881784197001252e-16,maxiter=100,full_output=False,disp=True])
使用"里德方法"(Ridder's Method)求解标量函数的根:[<x0>,<r>=]scipy.optimize.ridder(<f>,<a>,<b>[,args=(),xtol=2e-12,rtol=8.881784197001252e-16,maxiter=100,full_output=False,disp=True])
使用"二分法"(Bisection)求解标量函数的根:[<x0>,<r>=]scipy.optimize.bisect(<f>,<a>,<b>[,args=(),xtol=2e-12,rtol=8.881784197001252e-16,maxiter=100,full_output=False,disp=True])
使用"牛顿-拉夫逊方法"(Newton-Raphson Method)或"弦截法"(Secant Method)或"哈雷方法"(Halley's Method)求解标量函数的根:[<x0>,<r>=]scipy.optimize.newton(<func>,<x0>[,fprime=None,args=(),tol=1.48e-08,maxiter=50,fprime2=None,x1=None,rtol=0.0,full_output=False,disp=True])
使用"TOMS Algorithm 748 Method"求解标量函数的根:[<x0>,<r>=]scipy.optimize.toms748(<f>,<a>,<b>[,args=(),k=1,xtol=2e-12,rtol=8.881784197001252e-16,maxiter=100,full_output=False,disp=True])
- 求不动点:
求函数的"不动点"(Fixed Point):[<x>=]scipy.optimize.fixed_point(<func>,<x0>[,args=(),xtol=1e-08,maxiter=500,method='del2'])
#参数说明:
func:指定函数;为function
x0:指定初始解;为1×N array-like
args:指定要传给<func>的其他参数;为tuple
xtol:指定绝对终止误差;为float
#误差小于此值时终止
maxiter:指定最大迭代次数;为int
method:指定求解方法;为"del2"/"iteration"
x:返回不动点;为1×N ndarray
(2)向量函数寻根:
求解向量函数的根:[<sol>=]scipy.optimize.root(<fun>,<x0>[,args=(),method='hybr',jac=None,tol=None,callback=None,options=None])
#参数说明:
fun:指定函数;为callable
x0:指定初始解;为ndarray
args指定要传给<fun>的其他参数;为tuple
method:指定求解方法;为"hybr"/"lm"/"broyden1"/"broyden2"/"anderson"/"linearmixing"/"diagbroyden"/"excitingmixing"/"krylov"/"df-sane"
jac:用于告知<fun>的返回值;为bool/callable
tol:指定终止误差;为float
#误差小于此值时终止
callback:指定每次迭代结束后调用的回调函数;为callable
options:指定其他参数;为dict
sol:返回函数的根;为OptimizeResult
4.线性规划问题(Linear programming):
求解"线性规划问题"(Linear Programming;LP):[<res>=]scipy.optimize.linprog(<c>[,A_ub=None,b_ub=None,A_eq=None,b_eq=None,bounds=(0,None),method='interior-point',callback=None,options=None,x0=None])
#min c^T*x
#s.t. A_ub*x<=b_ub
# A_eq*x==b_eq
# lb<=x<=ub
#参数说明:
c:指定系数;为1D array-like
A_ub,A_eq:指定不等式/等式约束的系数矩阵;为2D array-like
b_ub,b_eq:指定不等式/等式约束的常数项;为1D array-like
bounds:指定变量范围;为(<lb>,<ub>),元素均为float/array-like
method:指定优化方法;为"highs-ds"/"highs-ipm"/"highs"/"interior-point"/"revised simplex"/"simplex"
callback:指定回调函数(每轮迭代至少调用1次);为callable
#"highs"方法不支持该参数
options:指定其他参数;为dict
#参数可为maxiter/disp/presolve
#除"highs"方法均支持tol/autoscale/rr/rr_method
x0:指定初始解;为1D array-like
res:返回规划结果;为scipy.optimize.OptimizeResult
5.指派问题(Assignment problems):
求解"线性和指派问题"(Linear Sum Assignment Problem):[<row_ind>,<col_ind>=]scipy.optimize.linear_sum_assignment(<cost_matrix>[,maximize=False])
#参数说明:
cost_matrix:指定"二分图"(Bipartite Graph)的"花费矩阵"(Cost Matrix);为array
maximize:为False,则进行"最小权匹配"(Minimum Weight Matching)
为True,则进行"最大权匹配"(Maximum Weight Matching)
row_ind,col_ind:返回指派方案;均为array
######################################################################################################################
求"二次分配问题"(Quadratic Assignment Problem)/"图匹配问题"(Graph Matching Problem)的近似解:[<res>=]scipy.optimize.quadratic_assignment(<A>,<B>[,method='faq',options=None])
#参数说明:
A,B:分别指定权重矩阵/距离矩阵;均为2D square array-like
method:指定求解方法;为"faq"/"2opt"
options:定其他参数;为dict
#参数可为maximize/partial_match/rng
res:返回结果;为OptimizeResult
6.其他
(1)有限差分近似(Finite-difference approximation;FDA):
扫描二维码关注公众号,回复:
12822667 查看本文章
标量函数梯度的有限差分近似:[<grad>=]scipy.optimize.approx_fprime(<xk>,<f>,<epsilon>[,*args])
检查梯度函数的准确性:[<err>=]scipy.optimize.check_grad(<func>,<grad>,<x0>[,*args,**kwargs])
#通过将梯度函数与梯度函数的有限差分近似进行比较来实现
(2)线搜索(Line search):
Bracket the minimum of the function:[<xa>,<xb>,<xc>,<fa>,<fb>,<fc>,<funcalls>=]scipy.optimize.bracket(<func>[,xa=0.0,xb=1.0,args=(),grow_limit=110.0,maxiter=1000])
Find alpha that satisfies strong Wolfe conditions:[<alpha>,<fc>,<gc>,<new_fval>,<old_fval>,<new_slope>=]scipy.optimize.line_search(<f>,<myfprime>,<xk>,<pk>[,gfk=None,old_fval=None,old_old_fval=None,args=(),c1=0.0001,c2=0.9,amax=None,extra_condition=None,maxiter=10])
(3)海塞近似(Hessian approximation):
Linear operator for the L-BFGS approximate inverse Hessian:class scipy.optimize.LbfgsInvHessProduct([*args,**kwargs])
Interface for implementing Hessian update strategies:class scipy.optimize.HessianUpdateStrategy
(4)基准问题(Benchmark problems):
The Rosenbrock function:[<f>=]scipy.optimize.rosen(<x>)
The derivative (i.e. gradient) of the Rosenbrock function:[<rosen_der>=]scipy.optimize.rosen_der(<x>)
The Hessian matrix of the Rosenbrock function:[<rosen_hess>=]scipy.optimize.rosen_hess(<x>)
Product of the Hessian matrix of the Rosenbrock function with a vector:[<rosen_hess_prod>=]scipy.optimize.rosen_hess_prod(<x>,<p>)