Механизм Attention для RNN
Модель Encoder-Decoder для реализации задачи Seq2Seq:
class Encoder(tf.keras.Model):
def __init__(self):
super().__init__()
self.embed = tf.keras.layers.Embedding(INPUT_VOCAB_SIZE, EMB_SIZE)
self.lstm = tf.keras.layers.LSTM(H_SIZE,
return_sequences=False,
return_state=True)
def call(self, x):
out = self.embed(x)
_, h, c = self.lstm(out)
state = (h, c)
return state
class Decoder(tf.keras.Model):
def __init__(self):
super().__init__()
self.embed = tf.keras.layers.Embedding(TARGET_VOCAB_SIZE, EMB_SIZE)
self.lstm = tf.keras.layers.LSTM(H_SIZE,
return_sequences=True,
return_state=True)
self.fc = tf.keras.layers.Dense(TARGET_VOCAB_SIZE, activation='softmax')
def call(self, x, init_state):
out = self.embed(x)
out, h, c = self.lstm(out, initial_state=init_state)
out = self.fc(out)
state = (h, c)
return out, state
Далее объединяем в единую систему:
encoder_model = Encoder()
decoder_model = Decoder()
encoder_inputs = tf.keras.layers.Input(shape=(None,))
decoder_inputs = tf.keras.layers.Input(shape=(None,))
enc_state = encoder_model(encoder_inputs)
decoder_outputs, _ = decoder_model(decoder_inputs, enc_state)
seq2seq = tf.keras.Model([encoder_inputs, decoder_inputs], decoder_outputs)
Имеется реализация механизма Attention от TensorFlow:
tf.keras.layers.Attention()
Вопрос: Как данную реализацию можно внедрить в имеющуюся систему, чтобы Attention отрабатывал?
Сломано множество копий, вариантов реализации и попыток.
Ни это - https://github.com/thushv89/attention_keras
Ни это - https://stackoverflow.com/questions/56946995/how-to-build-a-attention-model-with-keras
Ни это - https://www.tensorflow.org/tutorials/text/nmt_with_attention?hl=ru не работает.