原理引用
链接: https://blog.csdn.net/u011835903/article/details/107716390.
小结
对引用链接的小结
公式(1)(2)是灰狼算法模拟灰狼捕食的数学表示,但是在实际优化问题中,我们并不知道猎物(最优解)的位置,因此用α、β、δ三个较好的解来代替猎物的位置。所以最终代码中的数学模型是:
粒子群、灰狼小结
群智能体算法的相同点:①随机初始化可能解②其他解向初始解产生的较优解“靠近”(归根结底,这类算法似乎都是引用自然界种群的壳子,只是或多或少添加了种群的特征)。
不同点(灰狼、粒子群):粒子群算法中,其他的粒子由自身最优和全局最优,根据速度位置公式进行寻优(每次迭代中,全局最优粒子也会有速度和位置的变化);灰狼算法中,其他候补狼根据三个较好解更新位置,没有速度这个属性(每次迭代中,α、β、δ三个较好的解不会更新位置,只会在每次迭代结束时重新选择较好的灰狼)。
代码
①主函数main
clear all;
close all;
clc;
step = 0.01;
[N,D,Iter,x1,x2,y1,y2] = constant();
[wolves,alpha,beta,delta] = initialization(N,D,x1,x2,y1,y2);
% firstwolves = wolves;
wolves = iteration(Iter,N,D,wolves,alpha,beta,delta,x1,x2,y1,y2);
% figure(1);
% x = x1:0.1:x2;
% y = y1:0.1:y2;
% [X,Y] = meshgrid(x,y);
% Z = (X-1).^2 + (Y-1).^2;
% mesh(X,Y,Z);
% hold on;
% plot3(firstwolves(:,1), firstwolves(:,2), firstwolves(:,3), 'b*');
% hold on;
% plot3(wolves(:,1), wolves(:,2), wolves(:,3), 'r*');
% hold off;
②常数函数constant
function [N,D,Iter,x1,x2,y1,y2] = constant()
N = 30;
D = 2;
Iter = 200;
x1 = -50;
x2 = 50;
y1 = -50;
y2 = 50;
③初始化函数initialization
function [wolves,alpha,beta,delta] = initialization(N,D,x1,x2,y1,y2)
wolves(:,1) = (x2 - x1)*rand(N,1) + x1;
wolves(:,2) = (y2 - y1)*rand(N,1) + y1;
wolves(:,D+1) = fitness(wolves);
[alpha,beta,delta] = select(wolves,D);
④适应度函数fitness
function y = fitness(X)
y = -(X(:,1) - 1).^2 - (X(:,2) - 1).^2 + 5000;
⑤选择函数select
function [x,y,z] = select(X,D)
Y = X;
[~,x] = max(Y(:,D+1));
Y(x,D+1) = inf;
[~,y] = max(Y(:,D+1));
Y(y,D+1) = inf;
[~,z] = max(Y(:,D+1));
⑥迭代函数iteration
% 总结问题:①候选狼每个维度使用不同的参数根据三个最优狼进行捕猎
% ②对每个维度的位置有必要进行位置限制
function pos = iteration(Iter,N,D,pos,alpha,beta,delta,x1,x2,y1,y2)
firstwolves = pos;
for iter = 1:Iter
a = 2 - iter*(2/Iter);
for i = 1:N
if i~=alpha&&i~=beta&&i~=delta
for j = 1:D
c1 = 2*rand;d1 = sqrt(sum((c1*pos(alpha,j) - pos(i,j))^2));
c2 = 2*rand;d2 = sqrt(sum((c2*pos(beta,j) - pos(i,j))^2));
c3 = 2*rand;d3 = sqrt(sum((c3*pos(delta,j) - pos(i,j))^2));
a1 = a*(2*rand - 1); p1 = pos(alpha,j) - a1*d1;
a2 = a*(2*rand - 1); p2 = pos(beta,j) - a2*d2;
a3 = a*(2*rand - 1); p3 = pos(delta,j) - a3*d3;
pos(i,j) = (p1 + p2 + p3)/3;
if pos(i,1)>x2
pos(i,1) = x2;
end
if pos(i,1)<x1
pos(i,1) = x1;
end
if pos(i,2)>y2
pos(i,2) = y2;
end
if pos(i,2)<y1
pos(i,2) = y1;
end
end
end
end
pos(:,D+1) = fitness(pos);
[alpha,beta,delta] = select(pos,D);
figure(1);
x = x1:0.1:x2;
y = y1:0.1:y2;
[X,Y] = meshgrid(x,y);
Z = -(X-1).^2 - (Y-1).^2 + 5000;
mesh(X,Y,Z);
hold on;
plot3(firstwolves(:,1), firstwolves(:,2), firstwolves(:,3), 'b*');
hold on;
plot3(pos(:,1), pos(:,2), pos(:,3), 'r*');
hold off;
% show(X);
pause(0.2);
end
⑦狼群位置变化图像显示函数show
function show(X)
figure(2);
axis([-50 50 -50 50]);
hold on ;
grid on ;
cla;
plot(X(:,1),X(:,2),'r*');
hold off;