You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

训练准确率优异但Seq2Seq模型推理输出随机异常排查

问题描述

按照Keras字符级LSTM 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_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)
可能的原因分析
  • 推理输入预处理不匹配:训练时encoder_input_data对input_text做了one-hot编码并补空格,若推理用的X_test未遵循完全一致的预处理逻辑——比如未使用训练时的input_token_index映射字符、补空格长度不一致、遗漏字符编码——模型无法正确编码输入,输出必然随机。
  • 目标序列标记处理错误:若自定义数据集的target_text未添加训练逻辑依赖的起始符\t和终止符\n,训练时decoder的输入输出逻辑就会错位;反过来,若训练时加了标记,但推理时reverse_target_char_index未正确映射这两个字符,解码逻辑也会失效。
  • 推理模型层索引错误:代码中通过model.layers[2]、model.layers[3]获取LSTM层,依赖训练模型的层顺序与教程完全一致。若自定义训练时添加了额外层(如Dropout、BatchNormalization),层索引偏移会导致推理模型加载错误的权重,无法正常预测。
  • 字符映射表不一致:训练时的input_token_index、target_token_index、reverse_target_char_index需在推理时完整复用。若推理时重新生成映射表或加载出错,字符与索引的对应关系混乱,解码结果自然随机。
  • 测试集数据索引不匹配:推理时用X_test作为输入,但打印的是input_texts[seq_index],若两者索引不对应,或X_test的预处理序列与input_texts不匹配,会导致输入错误,输出随机。
  • 模型容量或训练不足:Seq2Seq训练用teacher forcing(decoder输入为完整目标序列),推理时需自主生成token。若latent_dim过小或训练轮数不足,模型可能仅记住训练数据的输入输出对应,未学到真正的序列映射规律,脱离teacher forcing后失效。

内容的提问来源于stack exchange,提问作者Wanderer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 13:59:57