I am trying to use tf.while_loop () to handle variable length inputs. However, I can only use it for a fixed length. The code no longer works after I changed the shape = (4) to the shape = (No). tf.dynamic_rnn seems to handle variable-length inputs. I'm not sure how tf.dynamic_rnn accomplishes this with tf.while_loop ().
import tensorflow as tf import numpy as np from tensorflow.python.ops import tensor_array_ops from tensorflow.python.ops import array_ops with tf.Graph().as_default(), tf.Session() as sess: initial_m = tf.Variable(0.0, name='m') inputs = tf.placeholder(dtype='float32', shape=(4))
(before change):
[array([ 0.5 , 0.75 , 0.875 , 0.9375], dtype=float32)]
output (after change):
Traceback (most recent call last): File "simple.py", line 26, in <module> [initial_t, initial_m, initial_outputs]) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2636, in while_loop result = context.BuildLoop(cond, body, loop_vars, shape_invariants) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2469, in BuildLoop pred, body, original_loop_vars, loop_vars, shape_invariants) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2450, in _BuildLoop _EnforceShapeInvariant(m_var, n_var) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.py", line 586, in _EnforceShapeInvariant % (merge_var.name, m_shape, n_shape)) ValueError: The shape for while/Merge_1:0 is not an invariant for the loop. It enters the loop with shape (), but has shape <unknown> after one iteration. Provide shape invariants using either the `shape_invariants` argument of tf.while_loop or set_shape() on the loop variables.