计算布尔张量中 "True" 值的数量

Count number of "True" values in boolean Tensor

我知道 tf.where 会 return True 值的位置,这样我就可以使用结果的 shape[0] 来获取 True 的数量]s。

但是,当我尝试使用它时,维度是未知的(这是有道理的,因为它需要在运行时计算)。所以我的问题是,如何访问维度并将其用于求和之类的操作?

例如:

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.

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

根据您的实际用例,如果您指定调用的缩减维度,您还可以计算每个 row/column 的总和。

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

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

为此,您可以使用 TensorFlow 的 shape-related operations, which act on the runtime value of the tensor. For example, tf.size(t) produces a scalar Tensor containing the number of elements in t, and tf.shape(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)

有一个 tensorflow 函数可以计算非零值 tf.count_nonzero。该函数还接受 axiskeep_dims 参数。

这是一个简单的例子:

import numpy as np
import tensorflow as tf
a = tf.constant(np.random.random(100))
with tf.Session() as sess:
    print(sess.run(tf.count_nonzero(tf.greater(a, 0.5))))

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

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