【问题标题】:How to do inference on seq2seq RNN?如何对 seq2seq RNN 进行推理?
【发布时间】:2021-03-02 12:26:50
【问题描述】:

我正在尝试使用 TensorFlow 中的 RNN 创建一个聊天机器人,使用此介绍 https://blog.keras.io/a-ten-minute-introduction-to-sequence-to-sequence-learning-in-keras.html

示例中的模型是基于字符的序列,但我想做一个单词级别的模型。本教程在“Bonus FAQ”部分提供了一些关于如何修改模型以使其成为单词级别的信息。我正在使用 GloVe 预训练的词嵌入。

我的模型如下所示:

emb_dimension = 100

# Set up embedding layer using pretrained weights
embedding_layer = Embedding(total_words, emb_dimension, input_length=max_input_len, weights=[embedding_matrix], name="Embedding")

# Set up input sequence
encoder_inputs = Input(shape=(None,))
x = embedding_layer(encoder_inputs)
encoder_lstm = LSTM(100, return_state=True)
x, state_h, state_c = encoder_lstm(x)
encoder_states = [state_h, state_c]

# Set up the decoder, using `encoder_states` as initial state.
decoder_inputs = Input(shape=(None,))
x = embedding_layer(decoder_inputs)
decoder_lstm = LSTM(100, return_sequences=True)
decoder_lstm(x, initial_state=encoder_states)

decoder_outputs = Dense(total_words, activation='softmax')(x)

# Define the model that will turn
# `encoder_input_data` & `decoder_input_data` into `decoder_target_data`
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary()

似乎训练得很好,但我不知道如何使用这个模型来处理新文本。本教程有一个推理示例,但这并没有针对单词级模型进行修改,我不知道该怎么做。特别是示例中的这一点:

encoder_model = Model(encoder_inputs, encoder_states)

decoder_state_input_h = Input(shape=(latent_dim,))
decoder_state_input_c = Input(shape=(latent_dim,))
decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]
decoder_outputs, state_h, state_c = decoder_lstm(
    decoder_inputs, initial_state=decoder_states_inputs)
decoder_states = [state_h, state_c]
decoder_outputs = decoder_dense(decoder_outputs)
decoder_model = Model(
    [decoder_inputs] + decoder_states_inputs,
    [decoder_outputs] + decoder_states)

我尝试修改此代码以添加嵌入层 x = embedding_layer(decoder_inputs),然后使用 x 作为解码器 lstm 的输入,但出现错误:TypeError: Cannot iterate over a Tensor with unknown first dimension.

如何设置推理模型?

【问题讨论】:

    标签: python tensorflow keras lstm seq2seq


    【解决方案1】:

    为推理编写解码器并不容易。首先,您必须了解您当前的解码器使用了teacher-forcing(这意味着在下一个时间步长的预测中给出了先前位置的正确标记)。对于推理,您将需要贪婪算法或光束搜索。本教程中描述了这些步骤:https://www.tensorflow.org/addons/tutorials/networks_seq2seq_nmt

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      • 2018-10-28
      相关资源
      最近更新 更多