LSTM多变量时序预测MATLAB代码模板

Posted 噢⊙▽⊙

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LSTM多变量时序预测MATLAB代码模板相关的知识,希望对你有一定的参考价值。

单序列:http://t.csdn.cn/GKZbW

LSTM时间序列预测,多输入单输出;

数据:https://pan.quark.cn/s/3548fcf2d502

%% 1.环境清理
clear, clc, close all;
%2.导入数据,多序列,多输入单输出
%有"自己设定"的一行,要根据自己数据设定值
D=readmatrix('副本data.xlsx');%"自己设定"
%要求一行为一组,最后一列为输出
data=D;
data1=data;
%% 3.数据处理
nn=130;%训练数据集大小,"自己设定"
numTimeStepsTrain = floor(nn);%nn数据训练 ,N-nn个用来验证
[data_in,PS_in]=mapminmax(data1(:,1:end-1)');
[data_out,PS_out]=mapminmax(data1(:,end)');
data=[data_in;data_out];
data=data';
[XTrain,YTrain,XTest] = shujuchuli(data,numTimeStepsTrain);
dataTest = data(numTimeStepsTrain+1:end,:);
YTest = dataTest(:,end)';
%% 4.定义LSTM结构参数
numFeatures= 6;%输入节点,"自己设定"
numResponses = 1;%输出节点
numHiddenUnits = 600;%隐含层神经元节点数 ,"自己设定"
 
%构建 LSTM网络 
layers = [sequenceInputLayer(numFeatures) 
 lstmLayer(numHiddenUnits) %lstm函数 
dropoutLayer(0.2)%丢弃层概率 
 reluLayer('name','relu')% 激励函数 RELU 
fullyConnectedLayer(numResponses)
regressionLayer];
 
XTrain=XTrain';
YTrain=YTrain';
 
%% 5.定义LSTM函数参数 
def_options();
%% 6.训练LSTM网络 
net = trainNetwork(XTrain,YTrain,layers,options);
 
%% 7.建立训练模型 
net = predictAndUpdateState(net,XTrain);
 
%% 8.仿真预测(训练集) 
%M = numel(XTrain);
M=length(XTrain(1,:));
for i = 1:M
    [net,YPred_1(:,i)] = predictAndUpdateState(net,XTrain(:,i),'ExecutionEnvironment','cpu');
end
T_sim1=mapminmax("reverse",YPred_1,PS_out);%预测结果去标准化 ,恢复原来的数量级 
%% 9.仿真预测(验证集) 
N=length(XTest(1,:));
for i = 1:N
    [net,YPred_2(:,i)] = predictAndUpdateState(net,XTest(:,i),'ExecutionEnvironment','cpu');%
end
T_sim2=mapminmax("reverse",YPred_2,PS_out);%预测结果去标准化 ,恢复原来的数量级 
%% 10.评价指标
%  均方根误差
T_train=data1(1:M,end)';
T_test=data1(M+1:end,end)';
error1 = sqrt(sum((T_sim1 - T_train).^2) ./ M);
error2 = sqrt(sum((T_sim2 - T_test ).^2) ./ N);
%  MAE
mae1 = sum(abs(T_sim1 - T_train)) ./ M ;
mae2 = sum(abs(T_sim2 - T_test )) ./ N ;
disp(['训练集数据的MAE为:', num2str(mae1)])
disp(['验证集数据的MAE为:', num2str(mae2)])
%  MAPE
maep1 = sum(abs(T_sim1 - T_train)./T_train) ./ M ;
maep2 = sum(abs(T_sim2 - T_test )./T_test) ./ N ;
disp(['训练集数据的MAPE为:', num2str(maep1)])
disp(['验证集数据的MAPE为:', num2str(maep2)])
%  RMSE
RMSE1 = sqrt(sumsqr(T_sim1 - T_train)/M);
RMSE2 = sqrt(sumsqr(T_sim2 - T_test)/N);
disp(['训练集数据的RMSE为:', num2str(RMSE1)])
disp(['验证集数据的RMSE为:', num2str(RMSE2)])
%% 11. 绘图
figure
subplot(2,1,1)
plot(T_sim1,'-s','Color',[255 0 0]./255,'linewidth',1,'Markersize',5,'MarkerFaceColor',[250 0 0]./255)
hold on 
plot(T_train,'-o','Color',[150 150 150]./255,'linewidth',0.8,'Markersize',4,'MarkerFaceColor',[150 150 150]./255)
legend( 'LSTM拟合训练数据','实际分析数据','Location','best');
title('LSTM模型预测结果及真实值','fontsize',12)
xlabel('样本','fontsize',12);
ylabel('数值','fontsize',12);
xlim([1 M])
%-------------------------------------------------------------------------------------
subplot(2,1,2)
bar((T_sim1 - T_train)./T_train)   
legend('LSTM模型训练集相对误差','Location','best')
title('LSTM模型训练集相对误差','fontsize',12)
ylabel('误差','fontsize',12)
xlabel('样本','fontsize',12)
xlim([1 M]);
%-------------------------------------------------------------------------------------
figure
subplot(2,1,1)
plot(T_sim2,'-s','Color',[0 0 255]./255,'linewidth',1,'Markersize',5,'MarkerFaceColor',[0 0 255]./255)
hold on 
plot(T_test,'-o','Color',[0 0 0]./255,'linewidth',0.8,'Markersize',4,'MarkerFaceColor',[0 0 0]./255)
legend('LSTM预测测试数据','实际分析数据','Location','best');
title('LSTM模型预测结果及真实值','fontsize',12)
xlabel('样本','fontsize',12);
ylabel('数值','fontsize',12);
xlim([1 N])
%-------------------------------------------------------------------------------------
subplot(2,1,2)
bar((T_sim2 - T_test )./T_test)   
legend('LSTM模型测试集相对误差','Location','NorthEast')
title('LSTM模型测试集相对误差','fontsize',12)
ylabel('误差','fontsize',12)
xlabel('样本','fontsize',12)
xlim([1 N]);
 
%% 12.预测新值
X=[50,30,6,200,20,8;71.5,22.5,0.2,300,90,35];%输入新的自变量组,一行为一组
X=mapminmax("apply",X',PS_in);
bzh_sim = yuceweilai(net,XTrain,X);
T_sim3=mapminmax("reverse",bzh_sim,PS_out)

shujuchuli.m

function [XTrain,YTrain,XTest] = shujuchuli(data,numTimeStepsTrain)
dataTrain = data(1:numTimeStepsTrain,:);% 训练样本
dataTest = data(numTimeStepsTrain+1:end,:); %验证样本  
XTrain = dataTrain(:,1:end-1);
YTrain = dataTrain(:,end);% 训练输出
XTest = dataTest(:,1:end-1);%测试输入 

XTest=XTest';
end

yuceweilai.m

function [T_sim3] = yuceweilai(net,XTrain,data_X)
net1 = resetState(net);
net1 = predictAndUpdateState(net1,XTrain);
P=size(data_X,2);
for i = 1:P
    [net1,YPred_3(i)] = predictAndUpdateState(net1,data_X(:,i),'ExecutionEnvironment','cpu');
end
T_sim3=YPred_3;
end

def_options.m

options = trainingOptions('adam', ... % adam优化算法 自适应学习率 
'MaxEpochs',500,...% 最大迭代次数 
 'MiniBatchSize',10, ...%最小批处理数量 
'GradientThreshold',1, ...%防止梯度爆炸 
'InitialLearnRate',0.005, ...% 初始学习率 
'LearnRateSchedule','piecewise', ...
 'LearnRateDropPeriod',125, ...%125次后 ,学习率下降 
'LearnRateDropFactor',0.2, ...%下降因子 0.2
'ValidationData',XTrain,YTrain, ...
 'ValidationFrequency',5, ...%每五步验证一次 
'Verbose',1, ...
 'Plots','training-progress');

运行结果:

 

 

 

 

 

以上是关于LSTM多变量时序预测MATLAB代码模板的主要内容,如果未能解决你的问题,请参考以下文章

LSTM时序预测基于matlab EMD结合LSTM风速数据预测含Matlab源码 2051期

LSTM时序预测基于matlab EMD结合LSTM风速数据预测含Matlab源码 2051期

LSTM时序预测基于matlab LSTM时间序列神经网络预测含Matlab源码 2267期

Matlab基于长短期记忆网络分类LSTM实现多分类预测(Excel可直接替换数据)

Matlab基于长短期记忆网络分类LSTM实现多分类预测(Excel可直接替换数据)

回归预测 | MATLAB实现GA-LSTM遗传算法优化长短期记忆网络的数据多输入单输出回归预测