使用粒子群进行优化
此示例说明如何使用 particleswarm
求解器进行优化。
此示例中的目标函数是德容的第五个函数,在运行此示例时可用。
dejong5fcn
此函数有 25 个局部最小值。
尝试使用默认 particleswarm
设置求该函数的最小值。
fun = @dejong5fcn; nvars = 2; rng default % For reproducibility [x,fval,exitflag] = particleswarm(fun,nvars)
Optimization ended: relative change in the objective value over the last OPTIONS.MaxStallIterations iterations is less than OPTIONS.FunctionTolerance.
x = 1×2
-31.9521 -16.0176
fval = 5.9288
exitflag = 1
解 x
是全局最优解吗?目前还不清楚。查看函数图可以看出,对于 [-50,50]
范围内的分量,函数有局部最小值。因此,将变量的范围限制在 [-50,50]
有助于求解器求出全局最小值。
lb = [-50;-50]; ub = -lb; [x,fval,exitflag] = particleswarm(fun,nvars,lb,ub)
Optimization ended: relative change in the objective value over the last OPTIONS.MaxStallIterations iterations is less than OPTIONS.FunctionTolerance.
x = 1×2
-16.0079 -31.9697
fval = 1.9920
exitflag = 1
这看起来很有希望:新解比以前的解具有更低的 fval
。但是,x
真的是全局解吗?尝试用更多粒子再次最小化,以更好地搜索该区域。
options = optimoptions('particleswarm','SwarmSize',100); [x,fval,exitflag] = particleswarm(fun,nvars,lb,ub,options)
Optimization ended: relative change in the objective value over the last OPTIONS.MaxStallIterations iterations is less than OPTIONS.FunctionTolerance.
x = 1×2
-31.9781 -31.9784
fval = 0.9980
exitflag = 1
这看起来更有希望。但此答案是全局解吗?它的准确性如何?用一个混合函数重新运行求解器。particleswarm
在 particleswarm
完成迭代后调用该混合函数。
options.HybridFcn = @fmincon; [x,fval,exitflag] = particleswarm(fun,nvars,lb,ub,options)
Optimization ended: relative change in the objective value over the last OPTIONS.MaxStallIterations iterations is less than OPTIONS.FunctionTolerance.
x = 1×2
-31.9783 -31.9784
fval = 0.9980
exitflag = 1
particleswarm
求出与之前基本相同的解。这使您对 particleswarm
报告的局部最小值和最终的 x
是全局解有了一些信心。