What is the unique function in TensorFlow?
A tensor is a data structure that represents matrices and vectors. It can be thought of as a multi-dimensional array.
The unique function in TensorFlow is used to find unique values in a tensor.
It takes the original tensor x. Then, it returns two tensors:
yidx
Tensor y contains the unique values from the original tensor. Tensor idx contains the index position where each unique value is found.
Tensor
yhas the same order of elements as in Tensorx.
Tensor
idxhas the same number of elements as in tensorx.
The illustration below shows how the unique function works in TensorFlow:
Syntax
The syntax of the unique function is as follows:
tf.unique(x, out_idx=tf.dtypes.int32, name=None)
Parameters
The unique function has three parameters:
x: A one-dimensional tensor.out_idx: Data type of the return tensor. Possible values includetf.int32andtf.int64. It istf.int32by default.name: A name for the operation.
Only the first parameter is compulsory. The rest are optional.
Return values
The unique function returns two tensors: y and idx.
Tensor y contains the unique values from the original tensor. Tensor idx contains the index position where each unique value is found.
Example
The code snippet below shows how the unique function is used in TensorFlow:
import tensorflow as tf# tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8]x = tf.constant([1,1,2,4,4,4,7,8,8])y, idx = tf.unique(x)print("x:", x) # => [1, 1, 2, 4, 4, 4, 7, 8, 8]print("y:", y) # => [1, 2, 4, 7, 8]print("idx", idx) # => [0, 0, 1, 2, 2, 2, 3, 4, 4]
Free Resources