Search code examples
tensorflowtheano

Tensorflow equivalent of Theano's extra_ops.Unique


How can I find the Tensorflow equivalent of Theano's extra_ops.Unique function?

tf.extra_ops.Unique(True, False, False)(la)[0].reshape([-1])

Solution

  • You can use tf.unique.

    • By default tf.unique returns a tuple (unique_elements, idx). That corresponds to theano.extra_ops.Unique(return_index=False, return_inverse=True, return_counts=False).

    • If you need return_counts=True, then you should use tf.unique_with_counts, which corresponds to theano.extra_ops.Unique(return_index=False, return_inverse=True, return_counts=True)

    • tf.unique does not support the return_index argument that Theano (through ) supports, but you can reproduce that behavior with the following function (fetched on that github issue):

      def unique_with_inverse(x):
        y, idx = tf.unique(x)
        num_segments = tf.shape(y)[0]
        num_elems = tf.shape(x)[0]
        return (y, tf.math.unsorted_segment_min(tf.range(num_elems), idx, num_segments))
      

      This function would correspond to theano.extra_ops.Unique(return_index=True, return_inverse=False, return_counts=False)