# Time Series Modeling with LSTM network¶

This tutorial shows how to use a LSTM recurrent neural network for predicting multivariate time series data in R’s mxnet package.

We employ an open source pollution dataset, the PM2.5 data of US Embassy in Beijing, where the goal is to forecast air pollution levels with data recorded over five years at the US embassy in Beijing, China. We use past PM2.5 concentration, dew point, temperature, pressure, wind speed, snow and rain to predict future PM2.5 concentration levels.

filename <- "pollution.csv"
if (!file.exists(filename)) {
destfile=filename, method='wget')
}


Note: The above command relies on wget. If the command fails, you can instead manually download the data from this link. After downloading, rename the resulting CSV file to the name specified by filename and move the file into the current working directory of our R session (use getwd() command to print this directory from the current R notebook).

After we have the data files in the right place, let’s load some required R packages and then preprocess the data:

require(mxnet)
if (!require(dplyr)) { install.packages('dplyr') }
if (!require(abind)) { install.packages('abind') }

## Extracting specific features from the dataset as variables for time series:
## We extract pollution, temperature, pressue, windspeed, snowfall and rainfall information
lines(1:num.epoch, logger$eval, col='red') legend("topright", legend = c("Train","Validation"), fill = c("blue","red"))  ## Inference on the network¶ Now that we have trained the network, let’s use it for inference. ## We extract the state symbols for RNN internals <- model$symbol$get.internals() sym_state <- internals$get.output(which(internals$outputs %in% "RNN_state")) sym_state_cell <- internals$get.output(which(internals$outputs %in% "RNN_state_cell")) sym_output <- internals$get.output(which(internals$outputs %in% "loss_output")) symbol <- mx.symbol.Group(sym_output, sym_state, sym_state_cell) ## We will predict 100 timestamps for 401st sample (first sample from the test samples) pred_length <- 100 predicted <- numeric() ## We pass the 400th sample through the network to get the weights and use it for predicting next ## 100 time stamps. data <- mx.nd.array(trainX[, , 400, drop = F]) label <- mx.nd.array(trainY[, 400, drop = F]) ## We create dataiterators for the input, please note that the label is required to create ## iterator and will not be used in the inference. You can use dummy values too in the label. infer.data <- mx.io.arrayiter(data = data, label = label, batch.size = 1, shuffle = FALSE) infer <- mx.infer.rnn.one(infer.data = infer.data, symbol = symbol, arg.params = model$arg.params,
aux.params = model$aux.params, input.params = NULL, ctx = ctx) ## Once we get the weights for the above time series, we try to predict the next 100 steps for ## this time series, which is technically our 401st time series. actual <- trainY[, 401] ## Now we iterate one by one to generate each of the next timestamp pollution values for (i in 1:pred_length) { data <- mx.nd.array(trainX[, i, 401, drop = F]) label <- mx.nd.array(trainY[i, 401, drop = F]) infer.data <- mx.io.arrayiter(data = data, label = label, batch.size = 1, shuffle = FALSE) ## note that we use rnn state values from previous iterations here infer <- mx.infer.rnn.one(infer.data = infer.data, symbol = symbol, ctx = ctx, arg.params = model$arg.params,
aux.params = model\$aux.params,
input.params = list(rnn.state = infer[[2]],
rnn.state.cell = infer[[3]]))

pred <- infer[[1]]
predicted <- c(predicted, as.numeric(as.array(pred)))

}


predicted contains the 100 prediction values output by our model. We plot the actual vs predicted values below.

plot(1:pred_length, predicted, type ="l", xlab="Time Steps", ylab="Values", col='blue',
ylim=c(min(c(actual,predicted)),max(c(actual,predicted))))
lines(1:pred_length, actual, col='red')
legend("topleft", legend = c("Actual","Predicted"), fill = c("blue","red"))


Note: This tutorial is merely for demonstration purposes and the network architectures and training hyperparameters have not been tuned extensively for accuracy.