You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow while_loop报错:Shape must be rank 0 but is rank 2 for 'while/LoopCond'

Fixing the 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 of now and pre individually. Since your inputs are 2x2 tensors, this outputs a 2x2 grid of True/False values.
  • 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 now is greater than pre: use tf.reduce_all()
  • If you want to loop if any element in now is greater than pre: use tf.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:01:46