LSTM编解码器推理模型

时间:2019-04-22 19:16:57

标签: keras lstm machine-translation encoder-decoder

许多基于LSTM的seq2seq编码器-解码器体系结构教程(例如英语-法语翻译)将模型定义如下:

encoder_inputs = Input(shape=(None,))
en_x=  Embedding(num_encoder_tokens, embedding_size)(encoder_inputs)

# Encoder lstm
encoder = LSTM(50, return_state=True)
encoder_outputs, state_h, state_c = encoder(en_x)

# We discard `encoder_outputs` and only keep the states.
encoder_states = [state_h, state_c]

# Set up the decoder, using `encoder_states` as initial state.
decoder_inputs = Input(shape=(None,))

# french word embeddings
dex=  Embedding(num_decoder_tokens, embedding_size)
final_dex= dex(decoder_inputs)

# decoder lstm
decoder_lstm = LSTM(50, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(final_dex,
                                     initial_state=encoder_states)

decoder_dense = Dense(num_decoder_tokens, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)

# While training, model takes eng and french words and outputs #translated french word
fullmodel = Model([encoder_inputs, decoder_inputs], decoder_outputs)

# rmsprop is preferred for nlp tasks
fullmodel.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['acc'])

fullmodel.fit([encoder_input_data, decoder_input_data], decoder_target_data,
          batch_size=128,
          epochs=100,
          validation_split=0.20)

然后为了进行预测,他们将推理模型定义如下:

# define the encoder model 
encoder_model = Model(encoder_inputs, encoder_states)
encoder_model.summary()


# Redefine the decoder model with decoder will be getting below inputs from encoder while in prediction
decoder_state_input_h = Input(shape=(50,))
decoder_state_input_c = Input(shape=(50,))
decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]
final_dex2= dex(decoder_inputs)

decoder_outputs2, state_h2, state_c2 = decoder_lstm(final_dex2, initial_state=decoder_states_inputs)

decoder_states2 = [state_h2, state_c2]
decoder_outputs2 = decoder_dense(decoder_outputs2)

# sampling model will take encoder states and decoder_input(seed initially) and output the predictions(french word index) We dont care about decoder_states2
decoder_model = Model(
    [decoder_inputs] + decoder_states_inputs,
    [decoder_outputs2] + decoder_states2)

然后使用以下方法进行预测:

# Reverse-lookup token index to decode sequences back to
# something readable.
reverse_input_char_index = dict(
    (i, char) for char, i in input_token_index.items())
reverse_target_char_index = dict(
    (i, char) for char, i in target_token_index.items())


def decode_sequence(input_seq):
    # Encode the input as state vectors.
    states_value = encoder_model.predict(input_seq)

    # Generate empty target sequence of length 1.
    target_seq = np.zeros((1,1))
    # Populate the first character of target sequence with the start character.
    target_seq[0, 0] = target_token_index['START_']

   # Sampling loop for a batch of sequences
    # (to simplify, here we assume a batch of size 1).
    stop_condition = False
    decoded_sentence = ''
    while not stop_condition:
        output_tokens, h, c = decoder_model.predict(
            [target_seq] + states_value)

        # Sample a token
        sampled_token_index = np.argmax(output_tokens[0, -1, :])
        sampled_char = reverse_target_char_index[sampled_token_index]
        decoded_sentence += ' '+sampled_char

        # Exit condition: either hit max length
        # or find stop character.
        if (sampled_char == '_END' or
           len(decoded_sentence) > 52):
            stop_condition = True

       # Update the target sequence (of length 1).
        target_seq = np.zeros((1,1))
        target_seq[0, 0] = sampled_token_index

        # Update states
        states_value = [h, c]
return decoded_sentence

我的问题是,他们训练了名称为“ fullmodel”的模型以获得最佳权重……在预测部分,他们使用了具有名称(encoder_model和decoder_model)的推理模型……所以他们没有使用任何“ fullmodel”的权重?!

我不明白他们如何从训练有素的模型中受益!

2 个答案:

答案 0 :(得分:1)

诀窍在于,所有内容都在同一变量范围内,因此变量被重用。

答案 1 :(得分:0)

如果您仔细注意,则已训练的图层权重将被重用。 例如,在创建解码器模型时,我们使用的是定义为完整模型一部分的解码器_lstm层, 解码器输出2,状态h2,状态c2 =解码器lstm(final_dex2,initial_state =解码器状态输入),

并且编码器模型也使用先前定义的coder_inputs和encoder_states层。 encoder_model =模型(encoder_inputs,encoder_states)

由于编码器-解码器模型的体系结构,我们需要执行这些实现技巧。 而且,正如keras文档中提到的那样,使用功能性API,可以很容易地重用经过训练的模型:通过在张量上调用任何模型,就可以将其视为层。 请注意,通过调用模型,您不仅可以重用模型的体系结构,还可以重用其权重。有关更多详细信息,请参阅-https://keras.io/getting-started/functional-api-guide/#all-models-are-callable-just-like-layers