1. 程式人生 > >MATLAB粒子群優化演算法實現(PSO)

MATLAB粒子群優化演算法實現(PSO)

PSO(PSO——Particle Swarm Optimization)(基於種群的隨機優化技術演算法)
粒子群演算法模仿昆蟲、獸群、鳥群和魚群等的群集行為,這些群體按照一種合作的方式尋找食物,群體中的每個成員通過學習它自身的經驗和其他成員的經驗來不斷改變其搜尋模式。

MATLAB程式碼:

%------初始格式化--------------------------------------------------
clear all;
clc;
format long;
%------給定初始化條件----------------------------------------------
c1=2
; %學習因子1 c2=2; %學習因子2 w=0.7298; %慣性權重 MaxDT=200; %最大迭代次數 % D=2; %搜尋空間維數(未知數個數) N=20; %初始化群體個體數目 %eps=10^(-6); %設定精度(在已知最小值時候用) Vmax=1; Vmin=-1; popmax=5; popmin=-5; %------初始化種群的個體(可以在這裡限定位置和速度的範圍)------------ for
i=1:N pop(i,:)=popmin+(popmax-popmin)*rand(1,2); %隨機初始化位置 V(i,:)=rand(1,2); %隨機初始化速度 fitness(i)=ackley(pop(i,:)); end %------先計算各個粒子的適應度,並初始化PiPg---------------------- [fitnessgbest bestindex]=min(fitness); gbest=pop(bestindex,:); pbest=pop; fitnesspbest=fitness; for
i=1:MaxDT for j=1:N V(j,:)=w*V(j,:)+c1*rand*(pbest(j,:)-pop(j,:))+c2*rand*(gbest-pop(j,:)); V(j,find(V(j,:)>Vmax))=Vmax; V(j,find(V(j,:)<Vmin))=Vmin; pop(j,:)=pop(j,:)+V(j,:); pop(j,find(pop(j,:)>popmax))=popmax; pop(j,find(pop(j,:)<popmin))=popmin; % if rand>0.8 % k=ceil(2*rand); % pop(j,k)=rand; % end fitness(j)=ackley(pop(j,:)); if fitness(j)<fitnesspbest(j) pbest(j,:)=pop(j,:); fitnesspbest(j)=fitness(j); end if fitness(j)<fitnessgbest gbest=pop(j,:); fitnessgbest=fitness(j); end end yy(i)=fitnessgbest; end %------最後給出計算結果 plot(yy) title(['適應度曲線 ' '終止次數=' num2str(MaxDT)]); xlabel('進化代數'); ylabel('適應度') %------演算法結束---DreamSun GL & HF-----------------------------------

優化的函式為ackley函式:

% ackley.m
% Ackley's function, from http://www.cs.vu.nl/~gusz/ecbook/slides/16
% and further shown at: 
% http://clerc.maurice.free.fr/pso/Semi-continuous_challenge/Semi-continuous_challenge.htm
%
% commonly used to test optimization/global minimization problems
%
% f(x)= [ 20 + e ...
%        -20*exp(-0.2*sqrt((1/n)*sum(x.^2,2))) ...
%        -exp((1/n)*sum(cos(2*pi*x),2))];
%
% dimension n = # of columns of input, x1, x2, ..., xn
% each row is processed independently,
% you can feed in matrices of timeXdim no prob
%
% example: cost = ackley([1,2,3;4,5,6])

function [out]=ackley(in)

% dimension is # of columns of input, x1, x2, ..., xn
 n=length(in(1,:));

 x=in;
 e=exp(1);

 out = (20 + e ...
       -20*exp(-0.2*sqrt((1/n).*sum(x.^2,2))) ...
       -exp((1/n).*sum(cos(2*pi*x),2)));
 return