我在 TensorFlow 2 中遇到AdditiveAttention()
层(即Bahdanau注意力(的错误,我不完全理解。我想训练一个聊天机器人,在两个Question
和Answer
数据集上训练一个seq2seq注意力模型。
我的问题由我尝试将注意力层添加到模型时遇到的错误表示。这是我的构建函数:
def build_model():
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Embedding, LSTM, AdditiveAttention, Dense
# Input: get char embeddings
encoder_inputs = Input(shape=(200), name='encoder_inputs')
encoder_embedding = Embedding(60, 200, name='encoder_embedding')(encoder_inputs)
# LSTM Encoder receives Question - returns states
encoder_lstm = LSTM(units=64, return_state=True, name='encoder_lstm')
encoder_outputs, h, c = encoder_lstm(encoder_embedding)
encoder_states = [h, c]
# Bahdanau Attention
context_vector, attention_weights = AdditiveAttention([h, encoder_outputs])
# Decoder Embedding layer receives Answer as input (teacher forcing)
decoder_inputs = Input(shape=(None,), name='decoder_inputs')
decoder_embedding = Embedding(60, 200, name='decoder_embedding')(decoder_inputs)
concat = tf.concat([tf.expand_dims(context_vector, 1), decoder_embedding], axis=-1)
# Decoder LSTM layer is set with Encoder LSTM's states as initial state
decoder_lstm = LSTM(units=64, return_state=True, return_sequences=True, name='decoder_lstm')
decoder_outputs, _, _ = decoder_lstm(concat)
decoder_dense = Dense(units=60, activation='softmax', name='decoder_dense')
decoder_outputs = decoder_dense(decoder_outputs)
chatbot = Model(inputs=[encoder_inputs, decoder_inputs], outputs=[decoder_outputs])
return chatbot
当我使用以下命令运行函数时:
bot = build_model()
我收到以下错误:
TypeError: 'AdditiveAttention' object is not iterable
有人可以帮助我理解错误,并正确实现注意力 seq2seq 模型吗?
本周我遇到了同样的问题。似乎 tf.keras 加法注意力不返回注意力权重,只返回上下文向量。
因此,你只需要在调用AdditiveAttention((时消除"attention_weights",你应该很好。