In this tutorial we will use a neural network to forecast daily sea temperatures. This tutorial will be similar to tutorial Sea Temperature Convolutional LSTM Example. Recall, that the data consists of 2-dimensional temperature grids of 8 seas: Bengal, Korean, Black, Mediterranean, Arabian, Japan, Bohai, and Okhotsk Seas from 1981 to 2017. The raw data was taken from the Earth System Research Laboratory (https://www.esrl.noaa.gov/psd/) and preprocessed into CSV files. Each example consists of fifty 2-dimensional temperature grids, and every grid is represented by a single row in a CSV file. Thus, each sequence is represented by a CSV file with 50 rows.
For this task, we will use a convolutional LSTM neural network to forecast 10 days worth of sea temperatures following a given sequence of temperature grids. The network will be trained similarly to the network trained tutorial 15. But the evaluation will be handled differently (applied only to the 10 days following the sequences).
To download the data, we will create a temporary directory that will store the data files, extract the tar.gz file from the url, and place it in the specified directory
val DATA_URL ="https://dl4jdata.blob.core.windows.net/training/seatemp/sea_temp2.tar.gz"val DATA_PATH = FilenameUtils.concat(System.getProperty("java.io.tmpdir"), "dl4j_seas/")
We will then extract the data from the tar.gz file, recreate directories within the tar.gz file into our temporary directories, and copy the files from the tar.gz file.
Next we will convert the raw data (csv files) into DataSetIterators, which will be fed into a neural network. Our training data will have 1600 examples which will be represented by a single DataSetIterator, and the testing data will have 136 examples which will be represented by a separate DataSetIterator. The temperatures of the 10 days following the sequences in the training and testing data will be contained in a separate DataSetIterator as well.
val path = FilenameUtils.concat(DATA_PATH, "sea_temp/") // set parent directoryval featureBaseDir = FilenameUtils.concat(path, "features") // set feature directoryval targetsBaseDir = FilenameUtils.concat(path, "targets") // set label directoryval futureBaseDir = FilenameUtils.concat(path, "futures") // set futures directory
We first initialize CSVSequenceRecordReaders, which will parse the raw data into record-like format. Then the SequenceRecordReaderDataSetIterators can be created using the RecordReaders. Since each example has exactly 50 timesteps, an alignment mode of equal length is needed. Note also that this is a regression- based task and not a classification one.
The next task is to initialize the parameters for the convolutional LSTM neural network and then set up the neural network configuration.
val V_HEIGHT =13;val V_WIDTH =4;val kernelSize =2;val numChannels =1;
In the neural network configuraiton we will use the convolutional layer, subsampling layer, LSTM layer, and output layer in success. In order to do this, we need to use the RnnToCnnPreProcessor and CnnToRnnPreprocessor. The RnnToCnnPreProcessor is used to reshape the 3-dimensional input from [batch size, height x width of grid, time series length ] into a 4 dimensional shape [number of examples x time series length , channels, width, height] which is suitable as input to a convolutional layer. The CnnToRnnPreProcessor is then used in a later layer to convert this convolutional shape back to the original 3-dimensional shape.
val conf =new NeuralNetConfiguration.Builder() .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT) .seed(12345) .updater(new Adam()) .weightInit(WeightInit.XAVIER) .list() .layer(0, new ConvolutionLayer.Builder(kernelSize, kernelSize) .nIn(numChannels) //1 channel .nOut(7) .stride(2, 2) .activation(Activation.RELU) .build()) .layer(1, new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX) .kernelSize(kernelSize, kernelSize) .stride(2, 2).build()) .layer(2, new LSTM.Builder() .activation(Activation.SOFTSIGN) .nIn(21) .nOut(100) .gradientNormalization(GradientNormalization.ClipElementWiseAbsoluteValue) .gradientNormalizationThreshold(10) .build()) .layer(3, new RnnOutputLayer.Builder(LossFunction.MSE) .activation(Activation.IDENTITY) .nIn(100) .nOut(52) .gradientNormalization(GradientNormalization.ClipElementWiseAbsoluteValue) .gradientNormalizationThreshold(10) .build()) .inputPreProcessor(0, new RnnToCnnPreProcessor(V_HEIGHT, V_WIDTH, numChannels)) .inputPreProcessor(2, new CnnToRnnPreProcessor(3, 1, 7 )) .build();val net =new MultiLayerNetwork(conf);net.init();
Model Training
To train the model, we use 15 epochs and call the fit method of the MultiLayerNetwork.
// Train model on training setnet.fit( train, 15 );
Model Evaluation
We will now evaluate our trained model. Note that we will use RegressionEvaluation, since our task is a regression and not a classification task. We will only evaluate the model using the temperature of the 10 days following the given sequence of daily temperatures and not on the temperatures of the days in the sequence. This will be done using the rnnTimeStep() method of the MultiLayerNetwork.
val eval =new RegressionEvaluation();test.reset();future.reset();while(test.hasNext()) {val next = test.next();val features = next.getFeatures();var pred = Nd4j.zeros(1, 2);for(i <-0 to 49){ pred = net.rnnTimeStep(features.get(NDArrayIndex.all(), NDArrayIndex.all(), NDArrayIndex.interval(i,i+1))); }val correct = future.next();val cFeatures = correct.getFeatures();for(i <-0 to 9){ eval.evalTimeSeries(pred, cFeatures.get(NDArrayIndex.all(), NDArrayIndex.all(), NDArrayIndex.interval(i,i+1))); pred = net.rnnTimeStep(pred); } net.rnnClearPreviousState();}