基于pso优化LSTM的时序预测(matlab实战)

 1、结果展示

 

 

 

 

 部分代码

%%代码链接:https://mbd.pub/o/bread/Y52Tlp9y
%% 粒子群优化LSTM(PSO_LSTM)
clc
clear
close  all
%% 数据读取
geshu=200;%训练集的个数
%读取数据
shuru=xlsread('input.xlsx');
shuchu=xlsread('output.xlsx');
nn = randperm(size(shuru,1));%随机排序
% nn=1:size(shuru,1);%正常排序
input_train =shuru(nn(1:geshu),:);
input_train=input_train';
output_train=shuchu(nn(1:geshu),:);
output_train=output_train';
input_test =shuru(nn((geshu+1):end),:);
input_test=input_test';
output_test=shuchu(nn((geshu+1):end),:);
output_test=output_test';
% 1. 寻找最佳参数
NN=5;                   %初始化群体个数
D=2;                    %初始化群体维数,
T=10;                   %初始化群体最迭代次数
c1=2;                   %学习因子1
c2=2;                   %学习因子2
%用线性递减因子粒子群算法
Wmax=1.2; %惯性权重最大值
Wmin=0.8; %惯性权重最小值
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%每个变量的取值范围
ParticleScope(1,:)=[10 200];  % 中间层神经元个数
ParticleScope(2,:)=[0.01 0.15]; % 学习率
ParticleScope=ParticleScope';
%% 训练LSTM
net = trainNetwork(inputn,outputn,layers,options);
%% 预测
net = resetState(net);% 网络的更新状态可能对分类产生了负面影响。重置网络状态并再次预测序列。
[~,Ytrain]= predictAndUpdateState(net,inputn);
test_simu=mapminmax('reverse',Ytrain,dd);%反归一化
%测试集样本输入输出数据归一化
inputn_test=mapminmax('apply',input_test,bb);
[net,an]= predictAndUpdateState(net,inputn_test);
test_simu1=mapminmax('reverse',an,dd);%反归一化
error1=test_simu1-output_test;%测试集预测-真实
[~,Ytrain]= predictAndUpdateState(net,XValidation);
test_simuy=mapminmax('reverse',Ytrain,dd);%反归一化
%% 画图
figure
plot(output_train,'r-o','Color',[255 0 0]./255,'linewidth',0.8,'Markersize',4,'MarkerFaceColor',[255 0 0]./255)
hold on
plot(test_simu,'-s','Color',[0 0 0]./255,'linewidth',0.8,'Markersize',5,'MarkerFaceColor',[0 0 0]./255)
hold off
legend(["真实值" "预测值"])
xlabel("样本")
title("训练集")

figure
plot(YValidationy,'-o','Color',[255 255 0]./255,'linewidth',0.8,'Markersize',4,'MarkerFaceColor',[255 0 0]./255)
hold on
plot(test_simuy,'-s','Color',[0 0 0]./255,'linewidth',0.8,'Markersize',5,'MarkerFaceColor',[0 0 0]./255)
hold off
legend(["真实值" "预测值"])
xlabel("样本")
title("验证集")

figure
plot(output_test,'-o','Color',[0 0 255]./255,'linewidth',0.8,'Markersize',4,'MarkerFaceColor',[25 0 255]./255)
hold on
plot(test_simu1,'-s','Color',[0 0 0]./255,'linewidth',0.8,'Markersize',5,'MarkerFaceColor',[0 0 0]./255)
hold off
legend(["真实值" "预测值"])
xlabel("样本")
title("测试集")

 % 真实数据,行数代表特征数,列数代表样本数output_test = output_test;
T_sim_optimized = test_simu1;  % 仿真数据

num=size(output_test,2);%统计样本总数
error=T_sim_optimized-output_test;  %计算误差
mae=sum(abs(error))/num; %计算平均绝对误差
me=sum((error))/num; %计算平均绝对误差
mse=sum(error.*error)/num;  %计算均方误差
rmse=sqrt(mse);     %计算均方误差根
% R2=r*r;
tn_sim = T_sim_optimized';
tn_test =output_test';
N = size(tn_test,1);
R2=(N*sum(tn_sim.*tn_test)-sum(tn_sim)*sum(tn_test))^2/((N*sum((tn_sim).^2)-(sum(tn_sim))^2)*(N*sum((tn_test).^2)-(sum(tn_test))^2)); 

你可能感兴趣的:(预测,深度学习,深度学习,人工智能)