【问题标题】:How to add attention layer to seq2seq model on Keras如何在 Keras 上的 seq2seq 模型中添加注意力层
【发布时间】:2018-04-20 21:57:17
【问题描述】:

根据this的文章,我写了这个模型:

enc_in=Input(shape=(None,in_alphabet_len))
lstm=LSTM(lstm_dim,return_sequences=True,return_state=True,use_bias=False)
enc_out,h,c=lstm(enc_in)
dec_in=Input(shape=(None,in_alphabet_len))
decoder,_,_=LSTM(decoder_dim,return_sequences=True,return_state=True)(dec_in,initial_state=[h,c])
decoder=Dense(units=in_alphabet_len,activation='softmax')(decoder)
model=Model([enc_in,dec_in],decoder) 

如何在解码器之前为这个模型添加注意力层?

【问题讨论】:

标签: nlp deep-learning keras lstm attention-model


【解决方案1】:

你可以使用this repo

  1. 您需要pip install keras-self-attention
  2. 导入层from keras_self_attention import SeqSelfAttention
    • 如果要使用 tf.keras 而不是 keras,请在导入前添加以下内容os.environ['TF_KERAS'] = '1'
    • 确保您使用 keras 时忽略前面的标志,因为它会导致不一致
  3. 由于您使用的是 keras 函数式 API,

    enc_out, h, c = lstm()(enc_in)
    att = SeqSelfAttention()(enc_out)
    dec_in = Input(shape=(None, in_alphabet_len))(att)
    

    我希望这能回答你的问题,以及未来的读者

【讨论】:

  • 这是自我关注。然而,对于 seq2seq,您通常需要注意编码器和解码器状态。
  • 那么,你有什么建议?
  • 我不知道是否有用于 Bahdanau 或 Luong attention 的 Keras 包装器,但是有一个简洁的 TensorFlow 2.0 教程用于 seq2seq 的注意力翻译。 tensorflow.org/tutorials/text/nmt_with_attention
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-05
  • 1970-01-01
  • 1970-01-01
  • 2019-01-02
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多