In tensorflow, if we want to count the number of each value in a tensor, we can use tf.unique_with_counts() to implement. In this tutorial, we will use some examples to show you how to do.
Syntax
tf.unique_with_counts() is defined as:
tf.unique_with_counts( x, out_idx=tf.dtypes.int32, name=None )
As to input \(x\), it must be 1-D tensor.
This function will return three variables:
y, idx, count = tf.unique_with_counts(x)
Here
y: the unique value in tensor x
ids: the index id of value y in tensor x
count: the number of value y in x
Here is an example
# tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8] y, idx, count = unique_with_counts(x) y ==> [1, 2, 4, 7, 8] idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4] count ==> [2, 1, 3, 1, 2]
More examples:
import tensorflow as tf import numpy as np x = np.array([1.0, 2.0, 3.0, 1.1, 1.0, 3.0]) x = tf.convert_to_tensor(x, dtype= tf.float32) y, id, count = tf.unique_with_counts(x) init = tf.global_variables_initializer() init_local = tf.local_variables_initializer() with tf.Session() as sess: sess.run([init, init_local]) a =sess.run([y, id, count]) print(a)
Run this code, you will see these results:
[array([1. , 2. , 3. , 1.1], dtype=float32), array([0, 1, 2, 3, 0, 2], dtype=int32), array([2, 1, 2, 1], dtype=int32)]
From the result, we can find id and count is the int32.
How about input x is not 1-D tensor?
Look at this example:
import tensorflow as tf import numpy as np x = np.array([1.0, 2.0, 3.0, 1.1, 1.0, 3.0]) x = tf.convert_to_tensor(x, dtype= tf.float32) x = tf.reshape(x, [-1, 2]) y, id, count = tf.unique_with_counts(x) init = tf.global_variables_initializer() init_local = tf.local_variables_initializer() with tf.Session() as sess: sess.run([init, init_local]) a =sess.run([y, id, count]) print(a)
Here x will be 3*2 tensor. Running this code, you will get this error:
tensorflow.python.framework.errors_impl.InvalidArgumentError: unique expects a 1D vector.
[[{{node UniqueWithCounts}}]]
It means input x must be 1-D tensor.
This function will be used if you plan to compute center loss function.