【发布时间】: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