【问题标题】:keras input shape for multivariate LSTM用于多元 LSTM 的 keras 输入形状
【发布时间】:2018-08-07 07:41:48
【问题描述】:

我正在尝试在我有两个输入的 keras 中拟合 LSTM 模型

y 是形状为 (100,10) 的输出 x 是形状为 (100,20) 的输入

library(keras)

x_train_vec <- matrix(rnorm(2000), ncol = 20, nrow = 100)
x_train_arr <- array(data = x_train_vec, dim = c(nrow(x_train_vec), 1, 20))


y_train_vec <- matrix(rnorm(1000), ncol = 10, nrow = 100)
y_train_arr <- array(data = y_train_vec, dim = c(nrow(x_train_vec), 1, 10))


> dim(x_train_arr)
[1] 100   1  20
> dim(y_train_arr)
[1] 100   1  10

现在我想拟合 LSTM 模型

model <- keras_model_sequential()

model %>%
  layer_lstm(units            = 50, 
             input_shape      = c(1,10), 
             batch_size       = 1) %>% 
  layer_dense(units = 1)

model %>% 
  compile(loss = 'mae', optimizer = 'adam')

model %>% fit(x          = x_train_arr, 
              y          = y_train_arr, 
              batch_size = 1,
              epochs     = 10, 
              verbose    = 1, 
              shuffle    = FALSE)

但我收到此错误:

py_call_impl 中的错误(可调用,dots$args,dots$keywords):
ValueError:检查输入时出错:预期 lstm_21_input 有 形状 (1, 10) 但得到了形状 (1, 20) 的数组

如果我将输入大小更改为 c(1,20),我会得到:

py_call_impl 中的错误(可调用,dots$args,dots$keywords):
ValueError:检查目标时出错:预期dense_13有2 尺寸,但得到形状为 (100, 1, 10) 的数组

我也玩过不同的设置,但它从来没有用过。

【问题讨论】:

  • 你的keras版本是多少?
  • 你的密集层应该有 2 个维度而不是 3 个维度:观察数和类数。
  • @mtoto 我将密集层更改为units = 10,它只接受整数。但错误仍然存​​在。

标签: r keras lstm


【解决方案1】:

如果您的 Keras 版本

注意语法是针对python的,你需要找到R等价的。

【讨论】:

  • 我正在使用 keras >= 2.0
  • 奇怪,Dense 应该在默认情况下应用元素明智。也许python和R keras之间存在差异。尝试添加 TimeDistributed 包装器,看看它是否有效?
【解决方案2】:

我想出了如何让它工作:

x_train_vec <- matrix(rnorm(2000), ncol = 20, nrow = 100)
x_train_arr <- array(data = x_train_vec, dim = c(nrow(x_train_vec), 20, 1))


y_train_vec <- matrix(rnorm(1000), ncol = 10, nrow = 100)
y_train_arr <- array(data = y_train_vec, dim = c(nrow(x_train_vec), 10))


model <- keras_model_sequential()

model %>%
  layer_lstm(units            = 50, 
             input_shape      = c(20,1), 
             batch_size       = 1) %>% 
  layer_dense(units = 10)

model %>% 
  compile(loss = 'mae', optimizer = 'adam')

model %>% fit(x          = x_train_arr, 
              y          = y_train_arr, 
              batch_size = 1,
              epochs     = 10, 
              verbose    = 1, 
              shuffle    = FALSE)

【讨论】:

    猜你喜欢
    • 2021-10-25
    • 2018-02-27
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    相关资源
    最近更新 更多