Rewrite the code to continuously predict data that has been incremented by 2 at the end…
- User
Rewrite the code to continuously predict data that has been incremented by 2 at the end of nTimeStep. "clc clear all close all
% Stock Morket/Exchange Forecasing Using LSTM % A sequence-to-sequence regression LSTM Network. % This Example uses the data set of Tehran Stock in 2022.
%% Step1: load and Prepare Data
[Xtrain,YTrain,Params] = LoadPrepareData2();
%% Step2: Create a LSTM network NumHiddenUnits = 100; Layers = [ sequenceInputLayer(1)
lstmLayer(NumHiddenUnits,... "InputWeightsInitializer",'zeros',... 'RecurrentWeightsInitializer','he') fullyConnectedLayer(1) regressionLayer];%% Step3: Training Options maxEpochs = 4000; InitialLearnRate = 0.04; Options = trainingOptions("adam",... "Plots","training-progress",... 'MaxEpochs',maxEpochs,... 'InitialLearnRate',InitialLearnRate,... 'LearnRateSchedule','piecewise',... 'LearnRateDropPeriod',100,... 'LearnRateDropFactor',0.9,... 'ExecutionEnvironment','gpu',... 'Shuffle','never');
%% Step4: Train the Network
LstmNet = trainNetwork(Xtrain,YTrain,Layers,Options); %% Step5: Forecasting the Test Data nTimeStep = 38; YPredict = ForecastingWithPredictedValues(... LstmNet,Xtrain,nTimeStep,Params);
function [Xtrain,YTrain,Params] = LoadPrepareData2()
load Month_data\Data_Temp.mat
ts = timeseries(Data,TimeLabel); ts.Name = 'Close'; ts.TimeInfo.Format = 'mmm dd, yyyy'; figure plot(ts,'LineWidth',2) title('Mashhad dry bulb') % Data = rot90(rot90(Data)); Data = Data'; %% Devide Data into Train and Test TrainData = Data;
%% Standardize train and test Data
m = mean(TrainData); s = std(TrainData);
TrainData = (TrainData - m)/s; %% Prepare Inputs and responses Xtrain = TrainData(1:end-1); YTrain = TrainData(2:end);
Params.m = m; Params.s = s; end
function YPredict = ForecastingWithPredictedValues(LstmNet,Xtrain,nTimeStep,Params)
LstmNet = resetState(LstmNet); LstmNet = predictAndUpdateState(LstmNet,Xtrain); [LstmNet,YPredict(:,1)] = predictAndUpdateState(LstmNet,Xtrain(end));
for i = 2:nTimeStep
[LstmNet,YPredict(:,i)] = predictAndUpdateState(LstmNet,YPredict(:,i-1));%#okend
%% Unstandadize the predictions Xtrain = XtrainParams.s + Params.m; YPredict = YPredictParams.s + Params.m;
%% Plot
figure,plot(Xtrain,'LineWidth',2); hold on
idx = numel(Xtrain):(numel(Xtrain) + nTimeStep); plot(idx,[Xtrain(end) YPredict],"LineWidth",2,'LineStyle','-') xlabel('Time [Day]') ylabel('Close Values') title('LSTM Forecasting') legend('Observed','Forecasted')
end
"
- Assistant
clc clear all close all
% Stock Market/Exchange Forecasting Using LSTM % A sequence-to-sequence regression LSTM Network. % This Example uses the data set of Tehran Stock in 2022.
%% Step1: Load and Prepare Data
[Xtrain,YTrain,Params] = LoadPrepareData2();
%% Step2: Create a LSTM network NumHiddenUnits = 100; Layers = [ sequenceInputLayer(1)
lstmLayer(NumHiddenUnits,... "InputWeightsInitializer",'zeros',... 'RecurrentWeightsInitializer','he') fullyConnectedLayer(1) regressionLayer];%% Step3: Training Options maxEpochs = 4000; InitialLearnRate = 0.04; Options = trainingOptions("adam",... "Plots","training-progress",... 'MaxEpochs',maxEpochs,... 'InitialLearnRate',InitialLearnRate,... 'LearnRateSchedule','piecewise',... 'LearnRateDropPeriod',100,... 'LearnRateDropFactor',0.9,... 'ExecutionEnvironment','gpu',... 'Shuffle','never');
%% Step4: Train the Network
LstmNet = trainNetwork(Xtrain,YTrain,Layers,Options); %% Step5: Forecasting the Test Data nTimeStep = 38; YPredict = []; Xtest = Xtrain(end); LstmNet = resetState(LstmNet); for i = 1:nTimeStep Y = predict(LstmNet,Xtest); YPredict = [YPredict; Y]; Xtest = Y + 2; end
%% Unstandardize the predictions Xtrain = XtrainParams.s + Params.m; YPredict = YPredictParams.s + Params.m;
%% Plot figure,plot(Xtrain,'LineWidth',2); hold on idx = (numel(Xtrain)+2):(numel(Xtrain) + 2nTimeStep); Yplot = Xtrain(end) + (2:2:2nTimeStep); plot(idx,[Xtrain(end) Yplot],"LineWidth",2,'LineStyle','-') xlabel('Time [Day]') ylabel('Close Values') title('LSTM Forecasting') legend('Observed','Forecasted') grid on
function [Xtrain,YTrain,Params] = LoadPrepareData2()
load Month_data\Data_Temp.mat
ts = timeseries(Data,TimeLabel); ts.Name = 'Close'; ts.TimeInfo.Format = 'mmm dd, yyyy';
figure plot(ts,'LineWidth',2) title('Mashhad dry bulb')
Data = Data';
%% Divide Data into Train and Test TrainData = Data;
%% Standardize train and test Data m = mean(TrainData); s = std(TrainData); TrainData = (TrainData - m)/s;
%% Prepare Inputs and responses Xtrain = TrainData(1:end-1); YTrain = TrainData(2:end);
Params.m = m; Params.s = s; end
- User
this code give me this error "Error using plot Vectors must be the same length.
Error in ForecastingWithPredictedValues (line 44) plot(idx,[Xtrain(end) Yplot],"LineWidth",2,'LineStyle','-')
Error in MainStockForecating2 (line 46) YPredict = ForecastingWithPredictedValues(..."
- Assistant
The error is caused because
nTimeStepis used to determine the length of theidxvector, but this value is not updated in the function after incrementing the finalXtrainvalue by 2.To fix it, you can update the
nTimeStepvalue after incrementing the final value ofXtrainby 2 as shown below:%% Step5: Forecasting the Test Data nTimeStep = 38; Xtest = Xtrain(end) + 2; YPredict = []; LstmNet = resetState(LstmNet); for i = 1:nTimeStep Y = predict(LstmNet,Xtest); YPredict = [YPredict; Y]; Xtest = Y + 2; end nTimeStep = numel(YPredict);This will update the
nTimeStepvalue after the prediction is complete to ensure that theidxvector has the same length asYPredict. - User
this code give me this error "Error using plot Vectors must be the same length.
Error in ForecastingWithPredictedValues (line 46) plot(idx,[Xtrain(end) Yplot],"LineWidth",2,'LineStyle','-')
Error in MainStockForecating2 (line 46) YPredict = ForecastingWithPredictedValues(..."
- Assistant
The error is caused because the
idxvector being plotted has a length 2*nTimeStep, while theYplotvector that is being plotted alongside has a length of only nTimeStep.To fix this issue, you can modify the
idxvector to have the same length asYplotby changing the line that createsidxas shown below:idx = (numel(Xtrain)+2):(numel(Xtrain) + 2*nTimeStep-2);This will ensure that both
idxandYplothave the same length and theplotfunction can be called without issues.