Count number of “True” values in boolean Tensor

后端 未结 4 1403
粉色の甜心
粉色の甜心 2020-12-29 01:58

I understand that tf.where will return the locations of True values, so that I could use the result\'s shape[0] to get the number of <

4条回答
  •  长情又很酷
    2020-12-29 02:45

    Rafal's answer is almost certainly the simplest way to count the number of true elements in your tensor, but the other part of your question asked:

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

    To do this, you can use TensorFlow's 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) produces a 1D Tensor containing the size of t in each dimension.

    Using these operators, your program could also be written as:

    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)
    

提交回复
热议问题