上一次的博客中我将粒子群的搜索过程可视化了,并将其转存为了gif格式文件,这个过程我先在这里给大家讲一下:
1.首先pause(),是在每次绘图之后暂停一段时间,单位是秒,再进行下一次绘图;
2.而当要转存为gif文件时,这其实就是一种无声的视频文件,因此我们需要每一帧的图像,可以用pause,但是用drawnow更好,它的原理是保持当前窗口不变,继续下一次绘图。
因此将转存为gif的步骤加入到之前的代码中就是:
clc;clear;close all;
%% 初始化种群
f= @(x)x .* sin(x) .* cos(2 * x) - 2 * x .* sin(3 * x); % 函数表达式
N = 50; % 初始种群个数
d = 1; % 空间维数
ger = 100; % 最大迭代次数
limit = [0, 20]; % 设置位置参数限制
vlimit = [-1, 1]; % 设置速度限制
w = 0.8; % 惯性权重
c1 = 0.5; % 自我学习因子
c2 = 0.5; % 群体学习因子
for i = 1:d
x = limit(i, 1) + (limit(i, 2) - limit(i, 1)) * rand(N, d);%初始种群的位置
end
v = rand(N, d); % 初始种群的速度
xm = x; % 每个个体的历史最佳位置
ym = zeros(1, d); % 种群的历史最佳位置
fxm = zeros(N, 1); % 每个个体的历史最佳适应度
fym = -inf; % 种群历史最佳适应度
%% 群体更新
iter = 1;
record = zeros(ger, 1); % 记录器
while iter <= ger
fx = f(x) ; % 个体当前适应度
for i = 1:N
if fxm(i) < fx(i)
fxm(i) = fx(i); % 更新个体历史最佳适应度
xm(i,:) = x(i,:); % 更新个体历史最佳位置
end
end
if fym < max(fxm)
[fym, nmax] = max(fxm); % 更新群体历史最佳适应度
ym = xm(nmax, :); % 更新群体历史最佳位置
end
v = v * w + c1 * rand * (xm - x) + c2 * rand * (repmat(ym, N, 1) - x);% 速度更新
% 边界速度处理
v(v > vlimit(2)) = vlimit(2);
v(v < vlimit(1)) = vlimit(1);
x = x + v;% 位置更新
% 边界位置处理
x(x > limit(2)) = limit(2);
x(x < limit(1)) = limit(1);
record(iter) = fym;%最大值记录
x0 = 0 : 0.01 : 20;
plot(x0, f(x0), 'b-', x, f(x), 'ro');title('状态位置变化')
drawnow
frame = getframe(1);
im = frame2im(frame);
[A,map] = rgb2ind(im,256);
if iter == 1;
imwrite(A,map,'E:\培训\优化算法\pso.gif','gif','LoopCount',Inf,'DelayTime',0.1);
else
imwrite(A,map,'E:\培训\优化算法\pso.gif','gif','WriteMode','append','DelayTime',0.1);
end
iter = iter+1;
end
disp(['最大值:',num2str(fym)]);
disp(['变量取值:',num2str(ym)]);
另外,大家可以看到,种群历史最优值处我们初始化为了-inf,这是因为我们需要求最大值。但是如果要求最小值应该怎么办呢?最好不要将这里改成+inf,如果这样做,我们后面的最优值更新中全部要改成最小值和<,太麻烦。那么最好的方式就是直接在适应度处加上负号,这样的话就相当于求最小值了,只不过要将最后的最优值取反。
并且我们之前所写的只是一维问题优化,代码优化程度不高,对此我给出一份优化程度较高的代码,以应对多维优化问题:
问题是求21.5+x*sin(4*pi*x)+y*sin(20*pi*y),x=[-3,12.1];y=[4.1,5.8]的极值。
clc;clear;close all;tic
%% 参数设定
N = 500;
d = 2;
ger = 1000;
w = 0.8;
c1 = 0.9;
c2 = 0.9;
xlimit = [-3 12.1;4.1 5.8];
vlimit = [-1 1;-1 1];
%% 种群初始化
x = repmat(xlimit(:,1)',N,1)+repmat(diff(xlimit'),N,1).*rand(N,d);
v = repmat(vlimit(:,1)',N,1)+repmat(diff(vlimit'),N,1).*rand(N,d);
xm = x;
fxm = -inf*ones(N,1);
ym = xlimit(:,1)'+diff(xlimit').*rand(1,d);
fym = -inf;
%% 开始搜索
for i = 1 : ger
y = f(x);
for j = 1 : N
if y(j)>fxm(j)
fxm(j)=y(j);
xm(j,:) = x(j,:);
if y(j)>fym
fym = y(j);
ym = x(j,:);
end
end
end
v = w*v+c1*rand*(xm-x)+c2*rand*(repmat(ym,N,1)-x);
x = x+v;
x = min(x,repmat(xlimit(:,2)',N,1));
x = max(x,repmat(xlimit(:,1)',N,1));
v = min(v,repmat(vlimit(:,2)',N,1));
v = max(v,repmat(vlimit(:,1)',N,1));
end
toc
disp(['最优解为:',num2str(ym)]);
disp(['最优值为:',num2str(fym)]);
子函数为:
function y = f(x)
y = 21.5+x(:,1).*sin(4*pi*x(:,1))+x(:,2).*sin(20*pi*x(:,2));
end
另一篇不错的博客: https://blog.csdn.net/niuyongjie/article/details/1572814