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:
y
idx
Tensor y
contains the unique values from the original tensor. Tensor idx
contains the index position where each unique value is found.
Tensor
y
has the same order of elements as in Tensorx
.
Tensor
idx
has the same number of elements as in tensorx
.
The illustration below shows how the unique
function works in TensorFlow:
The syntax of the unique
function is as follows:
tf.unique(x, out_idx=tf.dtypes.int32, name=None)
The unique
function has three parameters:
x
: A one-dimensional tensor.out_idx
: Data type of the return tensor. Possible values include tf.int32
and tf.int64
. It is tf.int32
by default.name
: A name for the operation.Only the first parameter is compulsory. The rest are optional.
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.
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