【问题标题】:Concatenate LSTM with CNN with different tensors' dimentions in Keras在 Keras 中将 LSTM 与具有不同张量维度的 CNN 连接起来
【发布时间】:2019-02-08 20:36:22
【问题描述】:

这是我尝试使用连接操作合并的两个神经元网络。网络应该按照 1-good 和 0-bad 电影对 IMDB 电影评论进行分类

def cnn_lstm_merged():
       embedding_vecor_length = 32
       cnn_model = Sequential()
       cnn_model.add(Embedding(top_words, embedding_vecor_length, input_length=max_review_length))
       cnn_model.add(Conv1D(filters=32, kernel_size=3, padding='same', activation='relu'))
       cnn_model.add(MaxPooling1D(pool_size=2))
       cnn_model.add(Flatten())

       lstm_model = Sequential()
       lstm_model.add(Embedding(top_words, embedding_vecor_length, input_length=max_review_length))
       lstm_model.add(LSTM(64, activation = 'relu'))
       lstm_model.add(Flatten())

       merge = concatenate([lstm_model, cnn_model])
       hidden = (Dense(1, activation = 'sigmoid'))(merge)
       #print(model.summary())
       output = hidden.fit(X_train, y_train, epochs=3, batch_size=64)
       return output

但是当我运行代码时出现错误:

  File "/home/pythonist/Desktop/EnsemblingLSTM_CONV/train.py", line 59, in cnn_lstm_merged
    lstm_model.add(Flatten())
  File "/home/pythonist/deeplearningenv/lib/python3.6/site-packages/keras/engine/sequential.py", line 185, in add
    output_tensor = layer(self.outputs[0])
  File "/home/pythonist/deeplearningenv/lib/python3.6/site-packages/keras/engine/base_layer.py", line 414, in __call__
    self.assert_input_compatibility(inputs)
  File "/home/pythonist/deeplearningenv/lib/python3.6/site-packages/keras/engine/base_layer.py", line 327, in assert_input_compatibility
    str(K.ndim(x)))
ValueError: Input 0 is incompatible with layer flatten_2: expected min_ndim=3, found ndim=2
[Finished in 4.8s with exit code 1]

如何合并这两层?谢谢

【问题讨论】:

    标签: python keras deep-learning conv-neural-network lstm


    【解决方案1】:

    没有必要在LSTM之后使用Flatten,因为LSTM(默认情况下)只返回last状态而不是序列,即数据将具有形状为(BS, n_output),但Flatten 层需要(BS, a, b) 的形状,它将转换为(BS, a*b)

    因此,要么删除Flatten 层并仅使用最后一个状态,要么将return_sequences=True 添加到LSTM。这将使LSTM 返回所有输出,而不仅仅是最后一个输出,即(BS, T, n_out)

    编辑:另外,您创建最终模型的方式是错误的。请看this 示例;对你来说,应该是这样的:

      merge = Concatenate([lstm_model, cnn_model])
      hidden = Dense(1, activation = 'sigmoid')
      conc_model = Sequential()
      conc_model.add(merge)
      conc_model.add(hidden)
      conc_model.compile(...)
    
      output = conc_model .fit(X_train, y_train, epochs=3, batch_size=64)
    

    总而言之,使用Functional API 可能会更好。

    编辑 2:这是最终代码

    cnn_model = Sequential()
    cnn_model.add(Embedding(top_words, embedding_vecor_length, input_length=max_review_length))
    cnn_model.add(Conv1D(filters=32, kernel_size=3, padding='same', activation='relu'))
    cnn_model.add(MaxPooling1D(pool_size=2))
    cnn_model.add(Flatten())
    
    lstm_model = Sequential()
    lstm_model.add(Embedding(top_words, embedding_vecor_length, input_length=max_review_length))
    lstm_model.add(LSTM(64, activation = 'relu', return_sequences=True))
    lstm_model.add(Flatten())
    
    # instead of the last two lines you can also use
    # lstm_model.add(LSTM(64, activation = 'relu'))
    # then you do not have to use the Flatten layer. depends on your actual needs
    
    merge = Concatenate([lstm_model, cnn_model])
    hidden = Dense(1, activation = 'sigmoid')
    conc_model = Sequential()
    conc_model.add(merge)
    conc_model.add(hidden)
    

    【讨论】:

    • 我做到了,但我遇到了另一个错误:文件“/home/pythonist/deeplearningenv/lib/python3.6/site-packages/keras/engine/base_layer.py”,第 285 行,在 assert_input_compatibility str(inputs) + '.层的所有输入 ValueError: 层 concatenate_1 被调用时输入不是符号张量。收到的类型:。完整输入:[, ]。该层的所有输入都应该是张量。 [在 4.7 秒内完成,退出代码为 1]
    • 那是因为您正在尝试连接顺序模型。将其转换为功能性 keras 模型,然后连接。它肯定会起作用。 @SuleymanSuleyman-zade
    • @UpasanaMittal 您也可以使用旧的顺序模型来执行此操作(请参阅我的编辑),但仍然 - 使用函数式 API 更直观、更容易,这是正确的。
    • 对不起,如何转换呢?我尝试使用许多配置,但仍然存在尺寸不同且不一致的错误。
    • @SuleymanSuleyman-zade 我添加了代码的工作版本。
    猜你喜欢
    • 2023-03-05
    • 1970-01-01
    • 2019-04-15
    • 2017-09-22
    • 2021-04-04
    • 2022-01-22
    • 1970-01-01
    • 2018-10-29
    • 2019-09-17
    相关资源
    最近更新 更多