我的微信公众号名称:AI研究订阅号
微信公众号ID:MultiAgent1024
公众号介绍:主要研究强化学习、计算机视觉、深度学习、机器学习等相关内容,分享学习过程中的学习笔记和心得!期待您的关注,欢迎一起学习交流进步!
针对如下Rosenbrock函数(n=30),设计一种PSO算法进行求解。
代码解释
建立目标函数:
function [ result ] = func_objValue( pop )
a=pop(:,[2:30]);% 所求解函数
b=pop(:,[1:29]);
c=ones(1,30);
objValue =100*sum((a-b.^2).^2,2)+sum((pop-c).^2,2);
result = objValue ;
end
拟合
function [ result ] = func_fitness( pop )%控制函数正负性
objValue = func_objValue(pop);
result =objValue ;
end
主函数。
clear all ;
close all ;
clc ;
N = 900 ; % 种群规模
D = 30 ; % 粒子维度
T = 1000 ; % 迭代次数
Xmax = 30 ;
Xmin = -30 ;
C1 = 2; %1.5 学习因子1
C2 = 2 ; %1.5 学习因子2
W = 0.75 ; %0.8 惯性权重
Vmax = 0.1 ; %10 最大飞行速度
Vmin = -0.1 ; %-10 最小飞行速度
popx = rand(N,D)*(Xmax-Xmin)+Xmin ; % 初始化粒子群的位置(粒子位置是一个D维向量)
popv = rand(N,D)*(Vmax-Vmin)+Vmin ; % 初始化粒子群的速度(粒子速度是一个D维度向量)
% 初始化每个历史最优粒子
pBest = popx ;
pBestValue = func_fitness(pBest) ;
%初始化全局历史最优粒子
[gBestValue,index] = max(func_fitness(popx)) ;
gBest = popx(index,:) ;
for t=1:T
for i=1:N
% 更新个体的位置和速度
popv(i,:) = W*popv(i,:)+C1*rand*(pBest(i,:)-popx(i,:))+C2*rand*(gBest-popx(i,:)) ;
popx(i,:) = popx(i,:)+popv(i,:) ;
% 边界处理,超过定义域范围就取该范围极值
index = find(popv(i,:)>Vmax | popv(i,:)<Vmin);
popv(i,index) = rand*(Vmax-Vmin)+Vmin ;
index = find(popx(i,:)>Xmax | popx(i,:)<Xmin);
popx(i,index) = rand*(Xmax-Xmin)+Xmin ;
% 更新粒子历史最优
if func_fitness(popx(i,:))<pBestValue(i)
pBest(i,:) = popx(i,:) ;
pBestValue(i) = func_fitness(popx(i,:));
end
if pBestValue(i) < gBestValue
gBest = pBest(i,:) ;
gBestValue = pBestValue(i) ;
end
end
% 每代最优解对应的目标函数值
tBest(t) = func_objValue(gBest);
end
figure
plot(tBest);
xlabel('迭代次数') ;
ylabel('适应度值') ;
title('适应度进化曲线') ;
运行结果
完整代码,及其文档 后台回复:PSO。