如何使用 Keras IN R 实现简单而基本的多步骤 LSTM



考虑以下矩阵

x_train <- matrix(c(1,2,3,2,3,4,3,4,5,4,5,6,5,6,7),
                  nrow=5,
                  ncol=3,
                  byrow=T)
y_train <- matrix(c(2,3,4,3,4,5,4,5,6,5,6,7,6,7,8),
                  nrow=5,
                  ncol=3,
                  byrow=T)

x_train中的一行对应于预期的输出,也在相应的行中,以y_train为单位,如下所示:

X                Y   
123 (predict ->) 234
234 (predict ->) 345
345 (predict ->) 456

我想在 R 中实现一个 keras/tensorflow LSTM,它基于三个前一个值能够预测三个下一个值。怎么做?

没有人回答我。这是我能做的最好的事情。如果有人对如何改进有任何建议。

#import libraries
library(keras)
library(tensorflow)
#inputs
x_train <- matrix(c(1,2,3,2,3,4,3,4,5,4,5,6,5,6,7),
                  nrow=5,
                  ncol=3,
                  byrow=T)
#targets
y_train <- matrix(c(2,3,4,3,4,5,4,5,6,5,6,7,6,7,8),
                  nrow=5,
                  ncol=3,
                  byrow=T)
#prepare datasets
size_sample <- 5
size_obsx = 3
size_obsy = 3
size_feature = 1
dim(x_train) <- c(size_sample, size_obsx, size_feature)
#prepare model
batch_size = 1
units = 20
model <- keras_model_sequential() 
model%>%
  layer_lstm(units = units, batch_input_shape = c(batch_size, size_obsx, size_feature), stateful= TRUE)%>%
  layer_dense(units = size_obsy)

model %>% compile(
  loss = 'mean_squared_error',
  optimizer = optimizer_adam( lr= 0.02 , decay = 1e-6 ),  
  metrics = c('accuracy')
)
summary(model)
#train model
epochs = 50
for(i in 1:epochs ){
  model %>% fit(x_train, y_train, epochs=1, batch_size=batch_size, verbose=1, shuffle=FALSE)
  model %>% reset_states()
}
#generate input
input_test = c(2,3,4)
dim(input_test) = c(1, size_obsx, size_feature)
# forecast
yhat = model %>% predict(input_test, batch_size=batch_size)
#print results
print(input_test)
print(yhat)
#> print(input_test)
#, , 1
#
#     [,1] [,2] [,3]
#[1,]    2    3    4
#
#> print(yhat)
#         [,1]     [,2]     [,3]
#[1,] 3.138948 3.988917 5.036199

最新更新