jeremiedb commented on a change in pull request #12664: [MXNET-637] Multidimensional LSTM example for MXNetR URL: https://github.com/apache/incubator-mxnet/pull/12664#discussion_r220441976
########## File path: R-package/vignettes/MultidimLstm.Rmd ########## @@ -0,0 +1,358 @@ +LSTM time series example +============================================= + +This tutorial shows how to use an LSTM model with multivariate data, and generate predictions from it. For demonstration purposes, we used an opensource pollution data. You can find the data on [GitHub](https://github.com/dmlc/web-data/tree/master/mxnet/tinyshakespeare). +The tutorial is an illustration of how to use LSTM models with MXNetR. We are forecasting the air pollution with data recorded at the US embassy in Beijing, China for five years. + +Dataset Attribution: +"PM2.5 data of US Embassy in Beijing" (https://archive.ics.uci.edu/ml/datasets/Beijing+PM2.5+Data) +We want to predict pollution levels(PM2.5 concentration) in the city given the above dataset. + +```r +Dataset description: +No: row number +year: year of data in this row +month: month of data in this row +day: day of data in this row +hour: hour of data in this row +pm2.5: PM2.5 concentration +DEWP: Dew Point +TEMP: Temperature +PRES: Pressure +cbwd: Combined wind direction +Iws: Cumulated wind speed +Is: Cumulated hours of snow +Ir: Cumulated hours of rain +``` + +We use past PM2.5 concentration, dew point, temperature, pressure, wind speed, snow and rain to predict +PM2.5 concentration levels + +Load and pre-process the Data +--------- +Load in the data and preprocess it. It is assumed that the data has been downloaded in as csv file 'data.csv' locally. + + ```r + ## Loading required packages + library("readr") + library("dplyr") + library("mxnet") + library("abind") + ``` + + + + ```r + + mx.set.seed(1234) + ## Preprocessing steps + + Data <- read.csv(file="data.csv", header=TRUE, sep=",") + + ## Extracting specific features from the dataset as variables for time series + ## We extract pollution, temperature, pressue, windspeed, snowfall and rainfall information from dataset + + df <- data.frame(Data$pm2.5, Data$DEWP,Data$TEMP, Data$PRES, Data$Iws, Data$Is, Data$Ir) + df[is.na(df)] <- 0 + + ## Now we normalise each of the feature set to a range(0,1) + df <- matrix(as.matrix(df),ncol=ncol(df),dimnames=NULL) + rangenorm <- function(x){(x-min(x))/(max(x)-min(x))} + df <- apply(df,2, rangenorm) + df <- t(df) + ``` +For using multidimesional data with MXNetR. We need to convert training data to the form +(n_dim x seq_len x num_samples) and label should be of the form (seq_len x num_samples) or (1 x num_samples) +depending on the LSTM flavour to be used(one-to-one/ many-to-one). Please note that MXNetR currently supports only these two flavours of RNN. +We have used n_dim = 7, seq_len = 100 and num_samples = 430. + +```r +n_dim <- 7 +seq_len <- 100 +num_samples <- 430 +## extract only required data from dataset +trX<- df[1:n_dim, 25:(24+(seq_len * num_samples))] +## the label data(next PM2.5 concentration) should be one time step ahead of the current PM2.5 concentration + +trY<- df[1,26:(25+(seqlen*num_samples))] +## reshape the matrices in the format acceptable by MXNetR RNNs +trainX <- trX +dim(trainX) <- c(n_dim, seq_len, num_samples) +trainY <- trY +dim(trainY) <- c(seq_len, num_samples) + +``` + + + +Defining and training the network +--------- + +```r +batch.size <- 32 +# take first 300 samples for train - remaining 100 for evaluation +train_ids <- 1:300 +eval_ids<- 301:400 + +## create dataiterators +train.data <- mx.io.arrayiter(data = trainX[,,train_ids, drop = F], label = trainY[, train_ids], + batch.size = batch.size, shuffle = TRUE) + +eval.data <- mx.io.arrayiter(data = trainX[,,eval_ids, drop = F], label = trainY[, eval_ids], + batch.size = batch.size, shuffle = FALSE) + +## Create the symbol for RNN +symbol <- rnn.graph(num_rnn_layer = 2, Review comment: Since mxnet 1.3.1, cpu with dropout is supported in mx.symbol.RNN, which provides a more user friendly support for RNN. For example, the whole architecture could be built from scratch with: ``` data <- mx.symbol.Variable("data") label <- mx.symbol.Variable("label") data <- mx.symbol.swapaxes(data, dim1 = 0, dim2 = 1) RNN <- mx.symbol.RNN(data = data, state_size = 50, num_layers = 1, p = 0.2, state_outputs = T, mode = "lstm") data <- mx.symbol.swapaxes(data = RNN[[1]], dim1 = 0, dim2 = 1) decode <- mx.symbol.FullyConnected(data = data, num_hidden = 1, flatten = F) loss <- mx.symbol.LinearRegressionOutput(data = decode, label = label) ``` I think the above would provide a less intimidating introduction to RNN. ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected] With regards, Apache Git Services
