@sonal - 是的,这是可能的。因为,在测试的大部分时间里,我们感兴趣的是传递一个例子,而不是一堆数据。
所以,你需要的是,你需要传递单个示例的数组让我们说
test_index = [10 , 23 , 42 ,12 ,24, 50]
到一个 dynamic_rnn 。预测必须基于最终的隐藏状态。在 dynamic_rnn 内部,我认为您可以在训练中传递超出 max_length 的句子。如果不是,您可以编写一个自定义解码器函数,使用您在训练时获得的权重来计算 GRU 或 LSTM 状态。这个想法是您可以继续生成输出,直到达到测试用例的最大长度或直到模型生成“EOS”特殊令牌。我更喜欢你使用解码器,在你从编码器获得最终的隐藏状态后,这也会产生更好的结果。
# function to the while-loop, for early stopping
def decoder_cond(time, state, output_ta_t):
return tf.less(time, max_sequence_length)
# the body_builder is just a wrapper to parse feedback
def decoder_body_builder(feedback=False):
# the decoder body, this is where the RNN magic happens!
def decoder_body(time, old_state, output_ta_t):
# when validating we need previous prediction, handle in feedback
if feedback:
def from_previous():
prev_1 = tf.matmul(old_state, W_out) + b_out
a_max = tf.argmax(prev_1, 1)
#### Try to find the token index and stop the condition until you get a EOS token index .
return tf.gather(embeddings, a_max )
x_t = tf.cond(tf.equal(time, 0), from_previous, lambda: input_ta.read(0))
else:
# else we just read the next timestep
x_t = input_ta.read(time)
# calculate the GRU
z = tf.sigmoid(tf.matmul(x_t, W_z_x) + tf.matmul(old_state, W_z_h) + b_z) # update gate
r = tf.sigmoid(tf.matmul(x_t, W_r_x) + tf.matmul(old_state, W_r_h) + b_r) # reset gate
c = tf.tanh(tf.matmul(x_t, W_c_x) + tf.matmul(r*old_state, W_c_h) + b_c) # proposed new state
new_state = (1-z)*c + z*old_state # new state
# writing output
output_ta_t = output_ta_t.write(time, new_state)
# return in "input-to-next-step" style
return (time + 1, new_state, output_ta_t)
return decoder_body
# set up variables to loop with
output_ta = tensor_array_ops.TensorArray(tf.float32, size=1, dynamic_size=True, infer_shape=False)
time = tf.constant(0)
loop_vars = [time, initial_state, output_ta]
# run the while-loop for training
_, state, output_ta = tf.while_loop(decoder_cond,
decoder_body_builder(feedback = True),
loop_vars,
swap_memory=swap)
这只是一个sn-p代码,请尝试相应修改。更多详情请见https://github.com/alrojo/tensorflow-tutorial