%% LSTM network
%% import data
clc
clear
close all
%读取double格式数据
[num2,ax,ay] = xlsread('股票价格走势预测.xlsx',1);
num2(:,1:3) = [];
num= [];
panx=4;
mx = size(num2,1);
for ii = 1:mx-panx
num = [num;[reshape(num2(ii:ii+panx,:),1,(panx+1)*6)]];
end
n = randperm(length(num));
n=1:1400;
m = 1000;
input_train =num(n(1:m),1:29);%训练数据输出数据
output_train = num(n(1:m),30);%训练数据输入数据
input_test = num((m+1:1400),1:29);%测试数据输出数据
output_test = num((m+1:1400),30);%测试数据输入数据
[inputn,inputps]=mapminmax(input_train',-1,1);%训练数据的输入数据的归一化
[outputn,outputps]=mapminmax(output_train',-1,1);%训练数据的输出数据的归一化de
inputn_test=mapminmax('apply',input_test',inputps);
%% Define Network Architecture
% Define the network architecture.
numFeatures = 29;%输入层维度
numResponses = 1;%输出维度
% 200 hidden units
numHiddenUnits = 50;%第一层维度
% a fully connected layer of size 50 & a dropout layer with dropout probability 0.5
layers = [ ...
sequenceInputLayer(numFeatures)%输入层
lstmLayer(numHiddenUnits,'OutputMode','sequence')%第一层
fullyConnectedLayer(30)%链接层
dropoutLayer(0.2)%遗忘层
fullyConnectedLayer(numResponses)%链接层
regressionLayer];%回归层
% Specify the training options.
% Train for 60 epochs with mini-batches of size 20 using the solver 'adam'
maxEpochs = 60;%最大迭代次数
miniBatchSize = 20;%最小批量
% the learning rate == 0.01
% set the gradient threshold to 1
% set 'Shuffle' to 'never'
options = trainingOptions('adam', ... %解算器
'MaxEpochs',maxEpochs, ... %最大迭代次数
'MiniBatchSize',miniBatchSize, ... %最小批次
'InitialLearnRate',0.01, ... %初始学习率
'GradientThreshold',1, ... %梯度阈值
'Shuffle','every-epoch', ... %打乱顺序
'Plots','training-progress',... %画图
'Verbose',0); %不输出训练过程
%% Train the Network
net = trainNetwork(inputn,outputn,layers,options);%开始训练
%% Test the Network
y_pred = predict(net,inputn_test,'MiniBatchSize',20)';%测试仿真输出
y_pred=(mapminmax('reverse',y_pred',outputps))';
% y_pred0 = predict(net,inputn,'MiniBatchSize',1)';%训练拟合值
% y_pred0=(mapminmax('reverse',y_pred0',outputps))';
y_pred=(double(y_pred));
figure%打开一个图像窗口
plot(y_pred(:,1),'k-')%黑色实线,点的形状为*
hold on%继续画图
plot(output_test(:,1),'r--')%红色实线,点的形状为o
hold off%停止画图
title('测试图')%标题
ylabel('收盘价')%Y轴名称
legend('测试值','实际值')%标签
error1 = y_pred-output_test;%误差
figure
plot(error1(:,1),'k-')
title('收盘价测试误差图')
ylabel('误差')
[MSE,RMSE,MBE,MAE ] =MSE_RMSE_MBE_MAE(output_test,y_pred);
result_table = table;
result_table.sim = y_pred;
result_table.true = output_test;
writetable(result_table,'./结果.csv')
- 1
- 2
- 3
前往页