以布尔十位数表示的“真”值的计数

2024-05-15 05:56:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道tf.where将返回True值的位置,这样我就可以使用结果的shape[0]来获得True的数量

但是,当我尝试使用它时,维度是未知的(这是有意义的,因为它需要在运行时计算)。所以我的问题是,我怎样才能访问一个维度,并在一个操作中像求和一样使用它?

例如:

myOtherTensor = tf.constant([[True, True], [False, True]])
myTensor = tf.where(myOtherTensor)
myTensor.get_shape() #=> [None, 2]
sum = 0
sum += myTensor.get_shape().as_list()[0] # Well defined at runtime but considered None until then.

Tags: nonefalsetrueget数量tfaswhere
3条回答

您可以将值强制转换为浮点数并计算它们的和: tf.reduce_sum(tf.cast(myOtherTensor, tf.float32))

根据实际的用例,如果指定了调用的reduce维度,还可以计算每行/列的总和。

我认为这是最简单的方法:

In [38]: myOtherTensor = tf.constant([[True, True], [False, True]])

In [39]: if_true = tf.count_nonzero(myOtherTensor)

In [40]: sess.run(if_true)
Out[40]: 3

Rafal的答案几乎可以肯定是计算张量中true元素数量的最简单方法,但问题的另一部分是:

[H]ow can I access a dimension and use it in an operation like a sum?

为此,可以使用TensorFlow的shape-related operations,它作用于tensor的运行时值。例如,^{}生成标量Tensor,包含t中的元素数,^{}生成一维Tensor,包含每个维度中t的大小。

使用这些运算符,您的程序也可以编写为:

myOtherTensor = tf.constant([[True, True], [False, True]])
myTensor = tf.where(myOtherTensor)
countTrue = tf.shape(myTensor)[0]  # Size of `myTensor` in the 0th dimension.

sess = tf.Session()
sum = sess.run(countTrue)

相关问题 更多 >

    热门问题