keras - 嵌入层 mask_zero 在后续层导致异常

keras - embedding layer mask_zero causing exception at subsequent layers

我正在研究基于 this 论文的模型,由于 GlobalMaxPooling1D 层不支持遮罩,我遇到了异常。

我有一个 Embedding 层,mask_zero 参数设置为 True。但是,由于后续的 GlobalMaxPooling1D 层不支持遮罩,因此出现异常。例外情况是预料之中的,因为 the documentation of the Embedding layer 中实际上指出 具有 mask_zero = TrueEmbedding 层之后的任何后续层都应支持遮罩 .

但是,由于我正在处理其中单词数量可变的句子,因此我确实需要 Embedding 层中的掩码。 (即由于输入的长度不同)我的问题是,我应该如何改变我的模型,使掩蔽仍然是模型的一部分,并且不会在 GlobalMaxPooling1D 层引起问题?

下面是模型的代码。

model = Sequential()
embedding_layer = Embedding(dictionary_size, num_word_dimensions,
                            weights=[embedding_weights], mask_zero=True,
                            embeddings_regularizer=regularizers.l2(0.0001))
model.add(TimeDistributed(embedding_layer,
                          input_shape=(max_conversation_length, timesteps)))

model.add(TimeDistributed(Bidirectional(LSTM(m // 2, return_sequences=True,
                                             kernel_regularizer=regularizers.l2(0.0001)))))
model.add(TimeDistributed(Dropout(0.2)))
model.add(TimeDistributed(GlobalMaxPooling1D()))
model.add(Bidirectional(LSTM(h // 2, return_sequences = True,
                             kernel_regularizer=regularizers.l2(0.0001)),
                        merge_mode='concat'))
model.add(Dropout(0.2))
crf = CRF(num_tags, sparse_target=False, kernel_regularizer=regularizers.l2(0.0001))
model.add(crf)
model.compile(optimizer, loss = crf.loss_function, metrics=[crf.accuracy])

However, as I am processing sentences with variable number of words in them, I do need the masking in the Embedding layer.

您是否正在填充句子以使它们具有相同的长度?如果是这样,那么您可以让模型自行发现 0 是填充,因此应该忽略它,而不是使用掩码。因此,您不需要显式屏蔽。此方法还用于处理数据中的缺失值,如 .

中所建议