tensorflow:检查张量等级

tensorflow: check tensor rank

我想检查张量的等级。这是我的代码:

import tensorflow as tf
x = tf.constant([[0,1,0], [0,1,0]])
print(tf.rank(x))

它returns

Tensor("Rank_14:0", shape=(), dtype=int32)

其中 Rank_14:0 不断增长。 我希望它 return 2. 我做错了什么?

Rank_14:0 是返回的张量的名称而不是它的值,您需要在 Session 中评估张量以获得实际值:

with tf.Session() as sess:
    sess.run(tf.rank(x))

import tensorflow as tf
x = tf.constant([[0,1,0], [0,1,0]])
r = tf.rank(x)

sess = tf.InteractiveSession()
​
print("My tensor is: ", r)
print("The value of my tensor is: ", r.eval())

My tensor is:  Tensor("Rank_3:0", shape=(), dtype=int32)
The value of my tensor is:  2