PSO 算法代码摘抄。

原文地址:精通 MATLAB 最优化计算 第 2 版 Page 270

A PSO algorithm code excerpt.

Original source: Mastering MATLAB Optimization Computing, 2nd Edition, Page 270

引言

粒子群优化算法(Particle Swarm Optimization,PSO 算法)是一种进化计算技术,由 Eberhart 博士和 kennedy 博士发明,源于对鸟群捕食行为的研究科研人最大的谎言。 PSO 算法同遗传算法类似,是一种基于迭代的优化工具。系统初始化为一组随机解,通过迭代搜寻最优值。但是并没有遗传算法用的交叉以及变异,而是粒子在解空间追随最优的粒子进行搜索。

Introduction

Particle Swarm Optimization (PSO) is an evolutionary computation technique invented by Dr. Eberhart and Dr. Kennedy, originating from the study of the foraging behavior of bird flocksthe biggest lie of researchers. Similar to genetic algorithms, PSO is an iterative optimization tool. The system is initialized with a set of random solutions and searches for the optimum through iteration. However, unlike genetic algorithms, it does not use crossover or mutation; instead, particles follow the best particle in the solution space to search.

Matlab 实现

关于算法的公式推导部分建议自行查看原始论文或者相关书籍。

Matlab Implementation

For the derivation of the algorithm’s formulas, it is recommended to consult the original papers or related books yourself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

function [xm, fv] = PSO(fitness,N,c1,c2,w,M,D)
% 待优化的目标函数:fitness
% 粒子数目:N
% 学习因子1:c1
% 学习因子2:c2
% 惯性权重:w
% 最大迭代次数:M
% 自变量的个数:D
%
% 目标函数取最小值时的自变量值:xm
% 目标函数的最小值:fv

format long;
for i = 1:N
for j = 1:D
x(i,j) = randn; % 随机初始化位置
v(i,j) = randn; % 随机初始化速度
end
end

for i = 1:N
p(i) = fitness(x(i,:));
y(i,:) = x(i,:);
end


pg = x(N,:); % pg 为全局最优
for i = 1:N-1
if fitness(x(i,:)) < fitness(pg)
pg = x(i,:);
end
end

for t = 1:M
for i = 1:N % 速度、位移更新
v(i,:) = w*v(i,:) + c1*rand*(y(i,:)-x(i,:)) + c2*rand*(pg-x(i,:));
x(i,:) = x(i,:) + v(i,:);
if fitness(x(i,:)) < p(i)
p(i) = fitness(x(i,:));
y(i,:) = x(i,:);
end
if p(i) < fitness(pg)
pg = y(i,:);
end
end
pbest(t) = fitness(pg);
end

xm = pg';
fv = fitness(pg);

end