简体   繁体   English

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

[英]How to implement a simple and basic multi step LSTM with Keras IN R?

Considering the following matrices 考虑以下矩阵

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)

A line in x_train corresponds to an expected output, also in a respective line, in y_train, like this: x_train中的一行与y_train的相应行中的预期输出相对应,如下所示:

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

I want to implement a keras/tensorflow LSTM in R that based on three previous values is able to predict three next values. 我想在R中实现一个keras / tensorflow LSTM,它基于前三个值可以预测下三个值。 How to do this? 这个怎么做?

No one answered me. 没有人回答我。 This was the best I could do. 这是我能做的最好的。 If anyone has any suggestions on how to improve. 如果有人对如何改进有任何建议。

#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM