代码之家  ›  专栏  ›  技术社区  ›  spore234

多元LSTM的keras输入形状

  •  0
  • spore234  · 技术社区  · 6 年前

    我试图在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中的错误(可调用,点$args,点$keywords):
    值错误:检查输入时出错:期望lstm_21_输入具有 形状(1,10),但得到了形状为(1,20)的数组

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

    py_call_impl中的错误(可调用,点$args,点$keywords):
    值错误:检查目标时出错:期望密集度为13的值为2 维度,但得到了形状为(100,1,10)的数组

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

    2 回复  |  直到 6 年前
        1
  •  0
  •   VegardKT    6 年前

    如果Keras版本是<2.0,则需要使用model.add(TimeDistributed(Dense(1)))。

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

        2
  •  0
  •   spore234    6 年前

    我想出了办法:

    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)