% Solve an Input-Output Time-Series Problem with a Time Delay Neural Network
% Script generated by NTSTOOL.
% Created Fri May 13 12:56:01 CEST 2011
%
% This script assumes these variables are defined:
%
%   data_Input_Indicators - input time series.
%   data_Target_4day - target time series.

inputSeries = tonndata(data_Input_Indicators,false,false);
targetSeries = tonndata(data_Target_4day,false,false);

% Create a Time Delay Network
inputDelays = 0:9;
hiddenLayerSize = 20;
net = timedelaynet(inputDelays,hiddenLayerSize);

% Prepare the Data for Training and Simulation
% The function PREPARETS prepares timeseries data for a particular network,
% shifting time by the minimum amount to fill input states and layer states.
% Using PREPARETS allows you to keep your original time series data unchanged, while
% easily customizing it for networks with differing numbers of delays, with
% open loop or closed loop feedback modes.
[inputs,inputStates,layerStates,targets] = preparets(net,inputSeries,targetSeries);

% Setup Division of Data for Training, Validation, Testing
net.divideParam.trainRatio = 90/100;
net.divideParam.valRatio = 5/100;
net.divideParam.testRatio = 5/100;


% Train the Network
[net,tr] = train(net,inputs,targets,inputStates,layerStates);

% Test the Network
outputs = net(inputs,inputStates,layerStates);
errors = gsubtract(targets,outputs);
performance = perform(net,targets,outputs)

% View the Network
view(net)

% Plots
% Uncomment these lines to enable various plots.
%figure, plotperform(tr)
%figure, plottrainstate(tr)
%figure, plotresponse(targets,outputs)
%figure, ploterrcorr(errors)
%figure, plotinerrcorr(inputs,errors)

% Early Prediction Network
% For some applications it helps to get the prediction a timestep early.
% The original network returns predicted y(t+1) at the same time it is given x(t+1).
% For some applications such as decision making, it would help to have predicted
% y(t+1) once x(t) is available, but before the actual y(t+1) occurs.
% The network can be made to return its output a timestep early by removing one delay
% so that its minimal tap delay is now 0 instead of 1.  The new network returns the
% same outputs as the original network, but outputs are shifted left one timestep.
nets = removedelay(net);
[xs,xis,ais,ts] = preparets(nets,inputSeries,targetSeries);
ys = nets(xs,xis,ais);
earlyPredictPerformance = perform(net,tc,yc)
