R ValueError: Error when checking input: expected simple_rnn_input to have 3 dimensions, but got array with shape (1661, 3)

R ValueError: Error when checking input: expected simple_rnn_input to have 3 dimensions, but got array with shape (1661, 3)

这是我的代码:

used_time_period = "2009-01-01::2017-04-01"

data_used = data_input[used_time_period,]

split_coefficient = 0.8

train_set_rate = round(nrow(data_used) * split_coefficient)

data_train = data_used[1:train_set_rate,]

data_test = data_used[(train_set_rate + 1):nrow(data_used),]

model = keras_model_sequential() %>%

layer_simple_rnn(units = 75, input_shape = dim(data_train[,1:3]), activation = "relu", return_sequences = TRUE) %>% 
layer_dense(units = 2, activation = "relu")

model %>% compile(optimizer = "adam", loss = "binary_crossentropy", metrics = "binary_accuracy")

history = model %>% fit(x = data_train[,1:3], y = data_train[,4:5], epochs = 40, batch_size = 20)

我得到的错误是:

ValueError: Error when checking input: expected simple_rnn_input to have 3 dimensions, but got array with shape (1661, 3)

dim(data_train[,1:3]) = (1661, 3)

dim(data_train[,4:5]) = (1661, 2)

我做错了什么?

如错误消息所述,layer_simple_rnn 需要 3D 数组,但您使用的是 data.frame,这是一个 2D 数组(具有行和列的 table)。

根据 Keras documentation,循环层需要一个形状为 (batch_size, timesteps, input_dim) 的数组。假设每一列对应不同的日期(如果我错了请纠正我),这应该可以工作:

dim(data_train[, 1:3]) # [1] 10  3
X <- as.matrix(data_train[, 1:3]) # Convert to an array
dim(X) # [1] 10  3

dim(X) <- c(dim(X), 1)
dim(X) # [1] 10  3  1

# The same for Y
Y <- as.matrix(data_train[, 4:5])
dim(Y) <- c(dim(Y), 1)

现在 XY 有 3 个维度,您可以将它们提供给您的模型:

history = model %>% fit(x = X, y = Y, epochs = 40, batch_size = 20)