tensorflow - ValueError:decoder / while / Merge_12:0的形状不是循环的不变量

时间:2018-06-03 20:25:52

标签: tensorflow dynamic while-loop decode

我使用tf.contrib.seq2seq.dynamic_decode进行解码器训练

prediction, final_decoder_state, _ = dynamic_decode(
    custom_decoder
)

使用自定义解码器

custom_decoder = CustomDecoder(decoder_cell, helper, decoder_init_state)

和帮助

helper = CustomTrainingHelper(batch_size, targets, stop_targets,
                              num_outs, outputs_per_step, 1.0, False)

而dynamic_decoder会引发错误

Traceback (most recent call last):
  File "E:/tasks/text_to_speech/tts/tf_seq2seq.py", line 95, in <module>
    custom_decoder
  File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\contrib\seq2seq\python\ops\decoder.py", line 304, in dynamic_decode
    swap_memory=swap_memory)
  File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 3224, in while_loop
    result = loop_context.BuildLoop(cond, body, loop_vars, shape_invariants)
  File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 2956, in BuildLoop
    pred, body, original_loop_vars, loop_vars, shape_invariants)
  File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 2930, in _BuildLoop
    next_vars.append(_AddNextAndBackEdge(m, v))
  File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 688, in _AddNextAndBackEdge
    _EnforceShapeInvariant(m, v)
  File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 632, in _EnforceShapeInvariant
    (merge_var.name, m_shape, n_shape))
ValueError: The shape for decoder/while/Merge_12:0 is not an invariant for the loop. It enters the loop with shape (10, 1), but has shape (?, 1) after one iteration. Provide shape invariants using either the `shape_invariants` argument of tf.while_loop or set_shape() on the loop variables.

batch_size等于10.据我所知,问题出在tf.while_loop和batch_size中。以什么方式可以修复此错误?提前谢谢。

1 个答案:

答案 0 :(得分:1)

您提供的信息太少,无法说出具体内容。请在将来关注(https://stackoverflow.com/help/mcve)。

通常,此错误告诉您以下内容。默认情况下,TensorFlow会检查从while循环的一次迭代传递到下一次循环的变量不会改变形状。在您的情况下,decoder/while/Merge_12:0张量最初的形状为(10, 1)但在一次迭代后变为(?, 1),这意味着张量流不再能够推断出第一维的大小。

如果您知道第一个维度确实是10,则可以使用Tensor.set_shape告诉TensorFlow。