tf.while_loop报ValueError:两个结构元素数量不一致问题咨询
Fixing
tf.while_loop ValueError: Mismatched Structure Sizes Hey there! Let's unpack this error and build the loop you need step by step.
First, what do those "two structures" refer to?
The error is telling you that the structure of variables you pass into tf.while_loop as initial values doesn't match the structure of values your loop body function returns.
In TensorFlow's while_loop, consistency is key: if you start with, say, a list of two tensors ([current_count, total]), your body function must return exactly two tensors (same order, same shape and dtype). If you return an extra tensor, or miss one, you'll get this mismatch error.
Implementing a loop with a tf.placeholder as the condition
Since you want to use a placeholder i as your loop termination condition, here's a working example that follows all the rules:
import tensorflow as tf # Define your placeholder (assuming it's an integer scalar) i = tf.placeholder(tf.int32, shape=[]) # Define loop variables: let's track a counter and a running sum initial_vars = [tf.constant(0, tf.int32), tf.constant(0, tf.int32)] # [counter, sum] # Condition function: loop while counter < i def loop_cond(counter, sum_val): # Use the placeholder `i` directly in the condition return tf.less(counter, i) # Body function: increment counter, add to sum def loop_body(counter, sum_val): new_counter = tf.add(counter, 1) new_sum = tf.add(sum_val, new_counter) # Return the SAME structure as initial_vars: two tensors return [new_counter, new_sum] # Run the loop final_counter, final_sum = tf.while_loop(loop_cond, loop_body, initial_vars) # Test it with a session (for TF 1.x; adjust for TF 2.x eager execution if needed) with tf.Session() as sess: result = sess.run(final_sum, feed_dict={i: 5}) print(f"Sum from 1 to 5: {result}") # Outputs 15
Key checks to avoid the error:
- Structure matching: The
initial_varsand the return value ofloop_bodymust be identical in structure (same number of elements, same nested structure if using lists/dicts). - Shape/dtype consistency: Each tensor in the body's return must match the corresponding initial tensor's dtype and shape (or be compatible for dynamic shapes).
- Condition uses the placeholder: Make sure your
loop_condfunction references the placeholder correctly—since it's part of the graph, TensorFlow will handle feeding its value at runtime.
内容的提问来源于stack exchange,提问作者cps
相关产品推荐
相关产品推荐

