【问题标题】:Building an LSTM net with an embedding layer in Keras在 Keras 中构建带有嵌入层的 LSTM 网络
【发布时间】:2018-07-25 03:19:38
【问题描述】:

我想创建一个 Keras 模型,该模型包含一个嵌入层,然后是两个 dropout 为 0.5 的 LSTM,最后是一个带有 softmax 激活的密集层。

第一个 LSTM 应该将顺序输出传播到第二层,而在第二层中,我只对在处理完整个序列后获取 LSTM 的隐藏状态感兴趣。

我尝试了以下方法:

sentence_indices = Input(input_shape, dtype = 'int32')

embedding_layer = pretrained_embedding_layer(word_to_vec_map, word_to_index)

embeddings = embedding_layer(sentence_indices)
# Propagate the embeddings through an LSTM layer with 128-dimensional hidden state
X = LSTM(128, return_sequences=True, dropout = 0.5)(embeddings)

# Propagate X trough another LSTM layer with 128-dimensional hidden state
X = LSTM(128, return_sequences=False, return_state=True, dropout = 0.5)(X)

# Propagate X through a Dense layer with softmax activation to get back a batch of 5-dimensional vectors.
X = Dense(5, activation='softmax')(X)

# Create Model instance which converts sentence_indices into X.
model = Model(inputs=[sentence_indices], outputs=[X])

但是我收到以下错误:

ValueError: Layer dense_5 expects 1 inputs, but it received 3 input tensors. Input received: [<tf.Tensor 'lstm_10/TensorArrayReadV3:0' shape=(?, 128) dtype=float32>, <tf.Tensor 'lstm_10/while/Exit_2:0' shape=(?, 128) dtype=float32>, <tf.Tensor 'lstm_10/while/Exit_3:0' shape=(?, 128) dtype=float32>]

显然 LSTM 没有返回我期望的形状的输出。我该如何解决这个问题?

【问题讨论】:

    标签: neural-network keras lstm


    【解决方案1】:

    如果您设置了return_state=True,那么LSTM(...)(X) 会返回三项内容:输出、最后一个隐藏状态和最后一个单元格状态。

    所以不是X = LSTM(128, return_sequences=False, return_state=True, dropout = 0.5)(X),而是X, h, c = LSTM(128, return_sequences=False, return_state=True, dropout = 0.5)(X)

    有关示例,请参阅 here

    【讨论】:

    • 感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多