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 True
s.
However, when I try and use this, the dimension is unknown (which makes sense as it needs to be computed at runtime). So my question is, how can I access a dimension and use it in an operation like a sum?
For example:
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.
To count the number of TRUE entries, which here is 5, the formula =COUNTIF(A1:A6,TRUE) applied to the column should work, but it always returns the result 1. On the other hand, the formula =COUNTIF(A1:A6,FALSE) works correctly on a similar column got by pulling down FALSE. COUNTIF() works properly.
Use count_nonzero() to count True elements in NumPy array In Python, False is equivalent to 0 , whereas True is equivalent to 1 i.e. a non-zero value.
To count the true values in an array: Use the filter() method to iterate over the array. Check if each value is equal to true and return the result.
The countTrue() method of Booleans Class in Guava Library is used to count the number of values that are true in the specified boolean values passed as the parameter. Parameters: This method accepts the boolean values among which the true values are to be count.
You can cast the values to floats and compute the sum on them:
tf.reduce_sum(tf.cast(myOtherTensor, tf.float32))
Depending on your actual use case you can also compute sums per row/column if you specify the reduce dimensions of the call.
I think this is the easiest way to do it:
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'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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With