Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

Rewrite the code to continuously predict data that has been incremented by 2 at the end…

  1. 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));%#ok
    

    end

    %% 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

    "

  2. 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

  3. 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(..."

  4. Assistant

    The error is caused because nTimeStep is used to determine the length of the idx vector, but this value is not updated in the function after incrementing the final Xtrain value by 2.

    To fix it, you can update the nTimeStep value after incrementing the final value of Xtrain by 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 nTimeStep value after the prediction is complete to ensure that the idx vector has the same length as YPredict.

  5. 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(..."

  6. Assistant

    The error is caused because the idx vector being plotted has a length 2*nTimeStep, while the Yplot vector that is being plotted alongside has a length of only nTimeStep.

    To fix this issue, you can modify the idx vector to have the same length as Yplot by changing the line that creates idx as shown below:

    idx = (numel(Xtrain)+2):(numel(Xtrain) + 2*nTimeStep-2);
    

    This will ensure that both idx and Yplot have the same length and the plot function can be called without issues.