首页 > 解决方案 > 如何检查张量是张量流中的单个值?

问题描述

我想检查张量是否只是一个数字。有什么办法可以使这种检查比 更好shape == ()

tensor_number = tf.constant(1)
tensor_not_number = tf.constant([1])

print(tensor_number.shape == ())
print(tensor_not_number.shape == ())

>> True
>> False

标签: tensorflow

解决方案


标量张量的秩为零。我们可以tf.rank用来检查张量是否是标量。

a=tf.constant(np.random.rand(3,3,3))
b=tf.constant(np.random.rand())
c=tf.constant(np.random.rand(1))
tf.print(tf.rank(a))
tf.print(tf.rank(b))
tf.print(tf.rank(c))
if tf.rank(b) == 0:
  tf.print('b is a scalar')
'''
3
0
1
b is a scalar
'''

推荐阅读