This example shows how to optimize using theparticleswarm
solver.
The objective function in this example is De Jong’s fifth function, which is included with Global Optimization Toolbox software.
dejong5fcn
This function has 25 local minima.
Try to find the minimum of the function using the defaultparticleswarm
settings.
fun = @dejong5fcn; nvars = 2; rngdefault% 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
Is the solutionx
the global optimum? It is unclear at this point. Looking at the function plot shows that the function has local minima for components in the range[-50,50]
. So restricting the range of the variables to[-50,50]
helps the solver locate a global minimum.
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
This looks promising: the new solution has lowerfval
than the previous one. But isx
一个真正的全球解决方案吗?尽量减少again with more particles, to better search the region.
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
This looks even more promising. But is this answer a global solution, and how accurate is it? Rerun the solver with a hybrid function.particleswarm
calls the hybrid function afterparticleswarm
finishes its iterations.
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
found essentially the same solution as before. This gives you some confidence thatparticleswarm
reports a local minimum and that the finalx
is the global solution.