rstudio / keras3

R Interface to Keras
https://keras3.posit.co/
Other
830 stars 282 forks source link

Stuck at forecast using LSTM in R for future values. #1347

Open sohrabkhan1 opened 2 years ago

sohrabkhan1 commented 2 years ago

I am learning R and using LSTM to forecast PV solar power. I have a dataset of 1600 hours out of which I have made 1000 hours for training and 600 for testing. Now I have validated the model on the testing dataset. I want to forecast the next 200 hours using the LSTM model. But as I am learning R through the random posts, I have no idea what to do for the future forecast.

here is how I created arrays for input (wheredatalags = 1):

x.train = array(data = lag(cbind(train$power), datalags)[-(1:datalags), ], dim = c(nrow(train) - datalags, datalags, 1))
y.train = array(data = train$power[-(1:datalags)], dim = c(nrow(train)-datalags, 1))

x.test = array(data = lag(cbind( test$power), datalags)[-(1:datalags), ], dim = c(nrow(test) - datalags, datalags, 1))
y.test = array(data = test$power[-(1:datalags)], dim = c(nrow(test) - datalags, 1))

and the model:

library(keras)
model <- keras_model_sequential()

model %>%
  layer_lstm(units = 32,
             input_shape = c(datalags, 1), #input shape is 3D, samples(batchsize given), time steps, and features (1 for univaiate and n for multivariate)
             batch_size = batch.size,
             return_sequences = TRUE, #return sequence is true because we wish to add another layer.
             stateful = TRUE) %>%
  layer_dropout(rate = 0.5) %>%
  layer_lstm(units = 32,
             return_sequences = FALSE,
             stateful = TRUE) %>%
  layer_dropout(rate = 0.5) %>%
  layer_dense(units = 1)
`
`model %>%
  compile(loss = 'mse', optimizer = 'adam')

model

for(i in 1:1000){
  model %>% fit(x = x.train,
                y = y.train,
                batch_size = batch.size,
                epochs = 1,
                verbose = 0,
                shuffle = FALSE)
  model %>% reset_states()
}

and forecast using ; pred_out <- model %>% predict(x.test, batch_size = batch.size) %>% .[,1]

everything works fine till now but the next step which is for future forecast is out of my understanding. I need guidance for this.

t-kalinowski commented 2 years ago

Chapter 10 in the Deep Learning with R book is completely devoted to doing time series predictions with Keras in R. I highly recommend you checkout out the two links to the code and the book :)