Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the count of an element in a tensor in TensorFlow?

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?

like image 327
J.Doe Avatar asked Apr 10 '16 14:04

J.Doe


People also ask

How do you find the value of the inside of a tensor?

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.

How do you find the size of a tensor in Python?

Using size() method: The size() method returns the size of the self tensor. The returned value is a subclass of a tuple.

What is rank in TensorFlow?

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."


2 Answers

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
like image 67
Daniel Slater Avatar answered Oct 02 '22 05:10

Daniel Slater


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
like image 20
Salvador Dali Avatar answered Oct 02 '22 05:10

Salvador Dali