如何在Keras上添加注意层到seq2seq模型

时间:2017-11-08 09:25:22

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

根据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) 

如何在解码器之前将注意力层添加到此模型?

1 个答案:

答案 0 :(得分:0)

您可以使用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)
    

    我希望这能回答您的问题,以及以后的读者

相关问题