r - 如何使用 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
推荐阅读
- python-3.x - 如何使用 D-Bus 和 Python 3 读取通知
- c# - 如何解决此空引用错误?
- phpstorm - 如何在 HTML 模式下禁用 PhpStorm 扩展输入空间?
- java - 如何在 gradle 中声明导航图
- c# - 如何使用反射传递不同类型的属性值?
- visual-studio - 在 Visual Studio 2017 中禁用块的代码样式
- javascript - 在Javascript中将立体声音频转换为单声道
- ios - 如何将我的应用程序限制为仅适用于 iPhone
- excel - 如何在VBA excel上每隔n个字符拆分一个字符串?
- r-markdown - 如何解决:将变量从python块调用到R块时,Rmarkdown中的“错误:找不到对象'py'”