I want to get the count of an element in a tensor, for example, t = [1, 2, 0, 0, 0, 0]
(t
is a tensor). I can get the amount 4 of zeros by calling t.count(0)
in Python, but in TensorFlow, I can't find any functions to do this. How can I get the count of zeros?
We can access the value of a tensor by using indexing and slicing. Indexing is used to access a single value in the tensor. slicing is used to access the sequence of values in a tensor. we can modify a tensor by using the assignment operator.
Using size() method: The size() method returns the size of the self tensor. The returned value is a subclass of a tuple.
The rank of a tensor is the number of indices required to uniquely select each element of the tensor. Rank is also known as "order", "degree", or "ndims."
There isn't a built in count method in TensorFlow right now. But you could do it using the existing tools in a method like so:
def tf_count(t, val):
elements_equal_to_value = tf.equal(t, val)
as_ints = tf.cast(elements_equal_to_value, tf.int32)
count = tf.reduce_sum(as_ints)
return count
To count just a specific element you can create a boolean mask, convert it to int
and sum it up:
import tensorflow as tf
X = tf.constant([6, 3, 3, 3, 0, 1, 3, 6, 7])
res = tf.reduce_sum(tf.cast(tf.equal(X, 3), tf.int32))
with tf.Session() as sess:
print sess.run(res)
Also you can count every element in the list/tensor using tf.unique_with_counts;
import tensorflow as tf
X = tf.constant([6, 3, 3, 3, 0, 1, 3, 6, 7])
y, idx, cnts = tf.unique_with_counts(X)
with tf.Session() as sess:
a, _, b = sess.run([y, idx, cnts])
print a
print b
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