0

我正在尝试使本教程适应我的单变量数据,以学习 R 中的 LSTM 时间序列预测。我认为问题出在定义模型的步骤中,但我不知道我缺少什么

#Data
#function to create sliding windows training data with 16 time steps
train_sliding = create_dataset(data = kt_train_male_scaled, n_input = 16, n_out = 16)

X_train = train_sliding[[1]]; dim(X_train)
[1] 97 16

y_train = train_sliding[[2]]; dim(y_train)
[1] 97 16

#Array transformation to Keras LSTM
dim(X_train) = c(dim(X_train), 1); dim(X_train)
[1] 97 16 1

#Model in Keras - I THINK THE PROBLEM IN THIS STEP
X_shape2 = dim(X_train)[2] #16
X_shape3 = dim(X_train)[3] #1
batch_size = 1 

model <- keras_model_sequential() 
model%>%
  layer_lstm(units = 64, activation = "relu", batch_size = batch_size, input_shape = c(dim(X_train)[2], dim(X_train)[3]),stateful= TRUE)%>%
        layer_dense(units = 5, activation = "relu") %>%
  layer_dense(units = 1, activation = "relu")
summary(model)

model %>% compile(
  loss = 'mse',
  optimizer = optimizer_adam(lr= 0.01, decay = 1e-6 ),  
  metrics = c('mae')
)

Epochs = 100   
for(i in 1:Epochs ){
  model %>% fit(X_train, y_train, epochs=1, batch_size=batch_size, verbose=1, shuffle=FALSE)
  model %>% reset_states()
}

L = length(kt_test_male_scaled); scaler = Scaled$scaler; predictions = numeric(L)

当我运行下面的代码时,我收到一条警告消息WARNING:tensorflow:Model was constructed with shape (1, 16, 1) for input KerasTensor(type_spec=TensorSpec(shape=(1, 16, 1), dtype=tf.float32, name='lstm_95_input'), name='lstm_95_input', description="created by layer 'lstm_95_input'"), but it was called on an input with incompatible shape (1, 1, 1).

for(i in 1:L){
     X = kt_test_male_scaled[i]
     dim(X) = c(1,1,1) #I tried to change to c(1,16,1) but I still got error: dims [product 16] do not match the length of object [1]
     yhat = model %>% predict(X, batch_size=batch_size)
     # invert scaling
     yhat = invert_scaling(yhat, scaler,  c(-1, 1))
     # store
     predictions[i] <- yhat
}

我所有的预测都是一样的

predictions
 [1] 0.2654046 0.2654046 0.2654046 0.2654046 0.2654046 0.2654046 0.2654046 0.2654046 0.2654046 0.2654046 0.2654046 0.2654046 0.2654046 0.2654046
[15] 0.2654046 0.2654046
4

0 回答 0