版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_39286218/article/details/80465339
问题描述:
目标函数o=sum(x.^2),X的值取0/1,选取BPSO优化
文件目录:
BPSO.m
ObjectiveFunction.m
BPSO.m
clear all
close all
clc
% Define the details of the binary optimization problem
nVar = 20 ;
ub =ones(1,nVar);
lb = zeros(1,nVar);
fobj = @ObjectiveFunction;
% Define the PSO's paramters
noP = 30;
maxIter = 500;
wMax = 0.9;
wMin = 0.2;
c1 = 2;
c2 = 2;
vMax = (ub - lb) .* 0.2;
vMin = -vMax;
% Initialize the particles
for k = 1 : noP
Swarm.Particles(k).X = round ( (ub-lb) .* rand(1,nVar) + lb );
Swarm.Particles(k).V = zeros(1, nVar);
Swarm.Particles(k).PBEST.X = zeros(1,nVar);
Swarm.Particles(k).PBEST.O = inf;
Swarm.GBEST.X = zeros(1,nVar);
Swarm.GBEST.O = inf;
end
% Main loop
for t = 1 : maxIter
% Calcualte the objective value
for k = 1 : noP
currentX = Swarm.Particles(k).X;
Swarm.Particles(k).O = fobj(currentX);
if Swarm.Particles(k).O < Swarm.Particles(k).PBEST.O %update the PBEST
Swarm.Particles(k).PBEST.X = currentX;
Swarm.Particles(k).PBEST.O = Swarm.Particles(k).O;
end
if Swarm.Particles(k).O < Swarm.GBEST.O %update the GBEST
Swarm.GBEST.X = currentX;
Swarm.GBEST.O = Swarm.Particles(k).O;
end
end
% Update the X and V vectors
w = wMax - t .* ((wMax - wMin) / maxIter);
for k = 1 : noP
Swarm.Particles(k).V = w .* Swarm.Particles(k).V + c1 .* rand(1,nVar) .* (Swarm.Particles(k).PBEST.X - Swarm.Particles(k).X) ...
+ c2 .* rand(1,nVar) .* (Swarm.GBEST.X - Swarm.Particles(k).X);
index1 = find(Swarm.Particles(k).V > vMax); % Check velocities
index2 = find(Swarm.Particles(k).V < vMin);
Swarm.Particles(k).V(index1) = vMax(index1);
Swarm.Particles(k).V(index2) = vMin(index2);
% Sigmoid transfer function
s = 1 ./ (1 + exp(Swarm.Particles(k).V));
for d = 1 : nVar % Update position
r = rand();
if r < s(d)
Swarm.Particles(k).X(d) = 0;
else
Swarm.Particles(k).X(d) = 1;
end
end
end
outmsg = ['Iteration# ', num2str(t) , ' Swarm.GBEST.O = ' , num2str(Swarm.GBEST.O)];
disp(outmsg);
cgCurve(t) = Swarm.GBEST.O;
end
semilogy(cgCurve);
xlabel('Iteration#')
ylabel('Weight')
ObjectiveFunction.m
function [ o ] = ObjectiveFunction ( x )
o = sum (x .^ 2); % Sphere test function
end
结果:
Iteration# 164 Swarm.GBEST.O = 1
Iteration# 165 Swarm.GBEST.O = 1
Iteration# 166 Swarm.GBEST.O = 1
Iteration# 167 Swarm.GBEST.O = 0
Iteration# 168 Swarm.GBEST.O = 0
Iteration# 169 Swarm.GBEST.O = 0
Iteration# 170 Swarm.GBEST.O = 0
Iteration# 171 Swarm.GBEST.O = 0
Iteration# 172 Swarm.GBEST.O = 0
Iteration# 173 Swarm.GBEST.O = 0
心得:
1. varible的值只有0和1,ub, lb, Swarm.Particles(k).X均要做出调整;
2. 在PSO.m中,原迭代式X和V的关系要通过sigmoid函数建立s(V)并将s的值映射到X