如何使用Tensorflow计算布尔矩阵中True的数量?谢谢!
[[False True False False False True False False False False]
[False True False False False True False False False False]
[False True False False False True False False False False]
[False True False False False True False False False False]]
答案 0 :(得分:1)
将布尔值转换为tf.in32
并将它们相加
import tensorflow as tf
data = [
[False, True, False,False,False, True, False,False,False,False],
[False, True, False,False,False, True, False,False,False,False],
[False, True, False,False,False, True, False,False,False,False],
[False, True, False,False,False, True, False,False,False,False]
]
var = tf.Variable(data)
num_true = tf.reduce_sum(tf.cast(var, tf.int32))
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(sess.run(num_true))
8
答案 1 :(得分:0)
方法1:
In [29]: data = [
[False, True, False,False,False, True, False,False,False,False],
[False, True, False,False,False, True, False,False,False,False],
[False, True, False,False,False, True, False,False,False,False],
[False, True, False,False,False, True, False,False,False,False]
]
In [30]: if_true = tf.where(tf.equal(tf.constant(data), True))
# or just if_true = tf.where(tf.constant(data))
In [31]: sess.run(if_true).shape[0]
# only get the indices where the item is true, then the number of
# returned indices amounts to the number of True
Out[31]: 8
这种方法在某种程度上更好,例如计算出有多少个Falses等等。
方法2:
In [34]: if_true = tf.count_nonzero(tf.constant(data))
In [35]: sess.run(if_true)
Out[35]: 8