TensorFlow while_loop报错:Shape must be rank 0 but is rank 2 for 'while/LoopCond'
LoopCond Shape Error in TensorFlow while_loop Hey there! I see exactly what's causing that error—let's break it down and fix it.
The Root Problem
The cond function you passed to tf.while_loop must return a scalar boolean value (a rank 0 tensor), but right now your code is spitting out a 2x2 boolean tensor instead. Here's why:
tf.greater(now, pre)compares each element ofnowandpreindividually. Since your inputs are 2x2 tensors, this outputs a 2x2 grid ofTrue/Falsevalues.- TensorFlow's while loop needs a single "yes/no" signal to know whether to keep looping, not a whole matrix of booleans. That's exactly why you're getting the "Shape must be rank 0 but is rank 2" error.
How to Fix It
You need to collapse that element-wise boolean tensor into a single scalar. Pick the logic that matches your actual use case:
- If you want to loop only if every element in
nowis greater thanpre: usetf.reduce_all() - If you want to loop if any element in
nowis greater thanpre: usetf.reduce_any()
Here's the adjusted code with tf.reduce_all (swap it for reduce_any if that fits your needs better):
import tensorflow as tf # Added the missing import x = ([1.,2.], [2.,1.]) xtensor = tf.convert_to_tensor(x) A = xtensor B = xtensor def cond(now, pre): # Collapse element-wise comparison to a single scalar boolean return tf.reduce_all(tf.greater(now, pre)) def body(now, pre): return pre, now A, now = tf.while_loop(cond, body, [A, B]) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) A_val = sess.run(A) B_val = sess.run(B) now_val = sess.run(now) print("A:", A_val) print("B:", B_val) print("now:", now_val)
Quick Extra Tweaks
I added the missing import tensorflow as tf line (your original code didn't include it) and renamed the session-run variables to avoid overwriting the original tensors—small changes to keep things clean and functional.
内容的提问来源于stack exchange,提问作者Flo

