# 【matlab】基于粒子群PSO算法实现限定自变量取值范围下的函数寻优

3 篇文章 0 订阅

PSO.m

clc
clear
close all
P_train = data(1:16,1:3)';
T_train = data(1:16,4:5)';
[inputn, ps_input] = mapminmax(P_train,0,1);%归一化
[outputn, ps_target] = mapminmax(T_train,0,1);%归一化

%速度更新
c1 = 2;
c2 = 1.5;
%
maxgen = 50; %最大更新代数
sizepop = 20; %种群大小
%
Vmax = 1;  %规定速度的大小范围
Vmin = -1;
%种群初始化
popmax1 = 12;  %规定自变量x 的取值范围
popmin1 = 2;
for i = 1:sizepop
pop(i,1) = (popmax1-popmin1)*rand(1,1)+popmin1;
V(i,1) = 2*Vmax*rand(1,1)+Vmin;
end
popmax2 = 4;  %规定自变量x 的取值范围
popmin2 = 1;
for i = 1:sizepop
pop(i,2) = (popmax2-popmin2)*rand(1,1)+popmin2;
V(i,2) = 2*Vmax*rand(1,1)+Vmin;
end
popmax3 = 40;  %规定自变量x 的取值范围
popmin3 = 10;
for i = 1:sizepop
pop(i,3) = (popmax3-popmin3)*rand(1,1)+popmin3;
V(i,3) = 2*Vmax*rand(1,1)+Vmin;
end
for i = 1:sizepop
fitness(i) = fun(pop(i,:),ps_input,ps_target,net);
end

[best_fitness,best_index] = min(fitness);
zbest = pop(best_index,:);%群体最优个体
gbest = pop;%个体最优个体
fitness_gbest = fitness;%个体最优个体函数值
fitness_zbest = best_fitness;%群体最优函数值
%
w_start = 0.9;
w_end = 0.4;
for i = 1:maxgen
w = w_start - (w_start-w_end)*(i/maxgen)^2;
for j = 1:sizepop
%速度更新
V(j,:) = V(j,:) + c1*rand*(gbest(j,:)-pop(j,:)) + ...
c2*rand*(zbest-pop(j,:));
V(j,find(V(j,:)>Vmax)) = Vmax;
V(j,find(V(j,:)<Vmin)) = Vmin;
pop(j,:) = pop(j,:) + w*V(j,:);
end
for j=1:3
%粒子更新
if j==1
pop(find(pop(:,j)>popmax1),j) = popmax1;
pop(find(pop(:,j)<popmin1),j) = popmin1;
end
if j==2
pop(find(pop(:,j)>popmax2),j) = popmax2;
pop(find(pop(:,j)<popmin2),j) = popmin2;
end
if j==3
pop(find(pop(:,j)>popmax3),j) = popmax3;
pop(find(pop(:,j)<popmin3),j) = popmin3;
end

end
for j = 1:sizepop
fitness(j) = fun(pop(j,:),ps_input,ps_target,net);
end
%个体与种群极值更新
for j = 1:sizepop
%个体
if fitness(j) < fitness_gbest(j)
gbest(j,:) = pop(j,:);
fitness_gbest(j) = fitness(j);
end
%种群
if fitness(j) < fitness_zbest
zbest = pop(j,:);
fitness_zbest = fitness(j);
end
end
xx(i,:) = zbest;
result(i) = fitness_zbest;
end

%% 结果显示
plot(result);
title(['最优函数值：',num2str(fitness_zbest)]);
zbest


fun.m
bp模型的输出是2维的，所以这里分别进行处理，对每个输出都进行了寻优

function y = fun(x,ps_input,ps_target,net)
input_n = mapminmax('apply', x', ps_input);
an=sim(net,input_n);
BPoutput = mapminmax('reverse', an, ps_target); %反归一化
% y=BPoutput(1,1);%求MRR时用这个
y=BPoutput(2,1);%求Ra时用这个
end


• 0
点赞
• 4
收藏
觉得还不错? 一键收藏
• 1
评论
03-03
06-11 2万+
12-03 3868
12-03 997
12-03 6667
07-09 3902
05-25 1万+
05-20 65

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。