我正在按照Keras教程https://keras.io/examples/nlp/lstm_seq2seq/训练一个seq2seq模型,代码相同,但数据集不同。以下是主要模型代码,供参考:
数据准备的代码段:
for i, (input_text, target_text) in enumerate(zip(input_texts, target_texts)):
for t, char in enumerate(input_text):
encoder_input_data[i, t, input_token_index[char]] = 1.0
encoder_input_data[i, t + 1 :, input_token_index[" "]] = 1.0
for t, char in enumerate(target_text):
# decoder_target_data is ahead of decoder_input_data by one timestep
decoder_input_data[i, t, target_token_index[char]] = 1.0
if t > 0:
# decoder_target_data will be ahead by one timestep
# and will not include the start character.
decoder_target_data[i, t - 1, target_token_index[char]] = 1.0
decoder_input_data[i, t + 1 :, target_token_index[" "]] = 1.0
decoder_target_data[i, t:, target_token_index[" "]] = 1.0
培训:
# Define an input sequence and process it.
encoder_inputs = keras.Input(shape=(None, num_encoder_tokens))
encoder = keras.layers.LSTM(latent_dim, return_state=True)
encoder_outputs, state_h, state_c = encoder(encoder_inputs)
# 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 = keras.Input(shape=(None, num_decoder_tokens))
# We set up our decoder to return full output sequences,
# and to return internal states as well. We don't use the
# return states in the training model, but we will use them in inference.
decoder_lstm = keras.layers.LSTM(latent_dim, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_inputs, initial_state=encoder_states)
decoder_dense = keras.layers.Dense(num_decoder_tokens, activation="softmax")
decoder_outputs = decoder_dense(decoder_outputs)
# Define the model that will turn
# `encoder_input_data` & `decoder_input_data` into `decoder_target_data`
model = keras.Model([encoder_inputs, decoder_inputs], decoder_outputs)
model.summary()
下面是我得到的准确性:
Epoch 1/5
1920/1920 [==============================] - 818s 426ms/step - loss: 0.2335 - accuracy: 0.9319 - val_loss: 0.2244 - val_accuracy: 0.9350
Epoch 2/5
1920/1920 [==============================] - 947s 493ms/step - loss: 0.2032 - accuracy: 0.9410 - val_loss: 0.1976 - val_accuracy: 0.9430
Epoch 3/5
1920/1920 [==============================] - 879s 458ms/step - loss: 0.1799 - accuracy: 0.9482 - val_loss: 0.1807 - val_accuracy: 0.9483
Epoch 4/5
1920/1920 [==============================] - 832s 433ms/step - loss: 0.1599 - accuracy: 0.9545 - val_loss: 0.1570 - val_accuracy: 0.9562
Epoch 5/5
1920/1920 [==============================] - 774s 403ms/step - loss: 0.1442 - accuracy: 0.9594 - val_loss: 0.1580 - val_accuracy: 0.9548
下面是推理模型:
encoder_inputs = model.input[0] # input_1
encoder_outputs, state_h_enc, state_c_enc = model.layers[2].output # lstm_1
encoder_states = [state_h_enc, state_c_enc]
encoder_model = keras.Model(encoder_inputs, encoder_states)
decoder_inputs = model.input[1] # input_2
decoder_state_input_h = keras.Input(shape=(latent_dim,))
decoder_state_input_c = keras.Input(shape=(latent_dim,))
decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]
decoder_lstm = model.layers[3]
decoder_outputs, state_h_dec, state_c_dec = decoder_lstm(
decoder_inputs, initial_state=decoder_states_inputs
)
decoder_states = [state_h_dec, state_c_dec]
decoder_dense = model.layers[4]
decoder_outputs = decoder_dense(decoder_outputs)
decoder_model = keras.Model(
[decoder_inputs] + decoder_states_inputs, [decoder_outputs] + decoder_states
)
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, num_decoder_tokens))
# Populate the first character of target sequence with the start character.
target_seq[0, 0, target_token_index["\t"]] = 1.0
# 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, :]) #greedy approach
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 == "\n" or len(decoded_sentence) > max_decoder_seq_length:
stop_condition = True
# Update the target sequence (of length 1).
target_seq = np.zeros((1, 1, num_decoder_tokens))
target_seq[0, 0, sampled_token_index] = 1.0
# Update states
states_value = [h, c]
return decoded_sentence
for seq_index in range(5):
# Take one sequence (part of the training set)
# for trying out decoding.
input_seq = X_test[seq_index : seq_index + 1]
decoded_sentence = decode_sequence(input_seq)
print("-")
print("Input sentence:", input_texts[seq_index])
print("Decoded sentence:", decoded_sentence)
然而,我得到的输出几乎是随机的。这背后的原因是什么呢?在训练中准确率在提高,损失也在减少。
1条答案
按热度按时间j8yoct9x1#
在计算损失时,您可能忘记移动目标序列。
在训练时,解码器序列需要移位,使得第(n-1)个预测第n个单词。对于具有句首标记[BOS]和句尾标记[EOS]的序列w1 w2 w3 w4,如下所示:
一般来说:向解码器馈送没有最后一个令牌的目标序列,并计算关于没有第一个令牌的目标序列的损失。
如果不执行此操作,解码器如下所示:
该模型快速学习复制输入标记,并且丢失快速减少,但是该模型不学习翻译。
解码器的输入应为
decoder_inputs[:, :-1]
,在解码器序列的开头和结尾添加特殊符号后,目标应为decoder_inputs[:, 1:]
。