MATLAB实现PSO-RF粒子群算法优化随机森林多输入单输出回归预测
粒子群算法优化随机森林(PSO-RF)回归预测(Matlab完整程序和数据)
输入6个特征,输出1个,即多输入单输出;
运行环境Matlab2018及以上,运行主程序main即可,其余为函数文件无需运行,所有程序放在一个文件夹,data为数据集;
命令窗口输出RMSEP、MAE、R2、MAPE。
%% 定义粒子群算法参数
% N 种群 T 迭代次数
%% 随机初始化种群
D=dim; %粒子维数
c1=1.5; %学习因子1
c2=1.5; %学习因子2
w=0.8; %惯性权重
Xmax=ub; %位置最大值
Xmin=lb; %位置最小值
Vmax=ub; %速度最大值
Vmin=lb; %速度最小值
%%
%%%%%%%%%%%%%%%%初始化种群个体(限定位置和速度)%%%%%%%%%%%%%%%%
x=rand(N,D).*(Xmax-Xmin)+Xmin;
v=rand(N,D).*(Vmax-Vmin)+Vmin;
%%%%%%%%%%%%%%%%%%初始化个体最优位置和最优值%%%%%%%%%%%%%%%%%%%
p=x;
pbest=ones(N,1);
for i=1:N
pbest(i)=fobj(x(i,:));
end
%%%%%%%%%%%%%%%%%%%初始化全局最优位置和最优值%%%%%%%%%%%%%%%%%%
g=ones(1,D);
gbest=inf;
for i=1:N
if(pbest(i)<gbest)
g=p(i,:);
gbest=pbest(i);
end
end
%%%%%%%%%%%按照公式依次迭代直到满足精度或者迭代次数%%%%%%%%%%%%%
for i=1:T
i
for j=1:N
%%%%%%%%%%%%%%更新个体最优位置和最优值%%%%%%%%%%%%%%%%%
if (fobj(x(j,:))) <pbest(j)
p(j,:)=x(j,:);
pbest(j)=fobj(x(j,:));
end
%%%%%%%%%%%%%%%%更新全局最优位置和最优值%%%%%%%%%%%%%%%
if(pbest(j)<gbest)
g=p(j,:);
gbest=pbest(j);
end
%%%%%%%%%%%%%%%%%跟新位置和速度值%%%%%%%%%%%%%%%%%%%%%
v(j,:)=w*v(j,:)+c1*rand*(p(j,:)-x(j,:))...
+c2*rand*(g-x(j,:));
x(j,:)=x(j,:)+v(j,:);
%%%%%%%%%%%%%%%%%%%%边界条件处理%%%%%%%%%%%%%%%%%%%%%%
if length(Vmax)==1
for ii=1:D
if (v(j,ii)>Vmax) | (v(j,ii)< Vmin)
v(j,ii)=rand * (Vmax-Vmin)+Vmin;
end
if (x(j,ii)>Xmax) | (x(j,ii)< Xmin)
x(j,ii)=rand * (Xmax-Xmin)+Xmin;
end
end
else
for ii=1:D
if (v(j,ii)>Vmax(ii)) | (v(j,ii)< Vmin(ii))
v(j,ii)=rand * (Vmax(ii)-Vmin(ii))+Vmin(ii);
end
if (x(j,ii)>Xmax(ii)) | (x(j,ii)< Xmin(ii))
x(j,ii)=rand * (Xmax(ii)-Xmin(ii))+Xmin(ii);
end
end
end
end
%%%%%%%%%%%%%%%%%%%%记录历代全局最优值%%%%%%%%%%%%%%%%%%%%%
Convergence_curve(i)=gbest;%记录训练集的适应度值
%% 清空环境变量
warning off % 关闭报警信息
close all % 关闭开启的图窗
clear % 清空变量
clc % 清空命令行
tic
restoredefaultpath
%% 导入数据
P_train = xlsread('data','training set','B2:G191')';
T_train= xlsread('data','training set','H2:H191')';
% 测试集——44个样本
P_test=xlsread('data','test set','B2:G45')';
T_test=xlsread('data','test set','H2:H45')';
%% 划分训练集和测试集
M = size(P_train, 2);
N = size(P_test, 2);
f_ = size(P_train, 1);
%% 数据归一化
[p_train, ps_input] = mapminmax(P_train, 0, 1);
p_test = mapminmax('apply', P_test, ps_input);
[t_train, ps_output] = mapminmax(T_train, 0, 1);
t_test = mapminmax('apply', T_test, ps_output);
%% 参数初始化
pop=10; %种群数量
Max_iter=30; % 设定最大迭代次数
dim = 2;% 维度为2,即优化两个超参数
lb = [1,1];%下边界
ub = [20,20];%上边界
fobj = @(x) fun(x,p_train,t_train);
[Best_pos,Best_score,curve]=PSO(pop,Max_iter,lb,ub,dim,fobj); %开始优化
%% 提取最优参数
n_trees = Best_pos(1);
n_layer = Best_pos(2);
%% 转置以适应模型
p_train = p_train'; p_test = p_test';
t_train = t_train'; t_test = t_test';
%% 创建模型
model = regRF_train(p_train, t_train, n_trees, n_layer);
[1] https://blog.csdn.net/kjm13182345320/article/details/129215161
[2] https://blog.csdn.net/kjm13182345320/article/details/128105718