Open In App

Tensorflow.js tf.unique() Function

Improve
Improve
Like Article
Like
Save
Share
Report

Tensorflow.js is an open-source library that is being developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment.

The .unique() function is used to find unique elements along an axis of a tensor.

 Syntax:

tf.unique (x, axis?)

 Parameters :

  • x: It is a first tensor input that can be of type tf.Tensor, or TypedArray, or Array. Parameters can be of these types (int32, string, bool).
  • axis ( number ): It is a second tensor input which is optional. The axis of the tensor is used to find the unique elements.

 Return value : It returns the values and  indices.

Example 1: In this example, we are defining an input tensor of integer type and then printing the unique value of it. For creating an input tensor, we are utilizing the .tensor1d() method and in order to print the output we are using the .print() method.

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining tensor input elements
const a = tf.tensor1d([1, 1, 2, 2, 4, 4, 7, 7, 8]);
  
// Calling unique() method 
const {values, indices} = tf.unique(a);
  
// Printing the values and indices 
values.print();   // [1, 2, 4, 7, 8,]
indices.print();  // [0, 0, 1, 1, 2, 2, 3, 3, 4]


Output:

Tensor
    [1, 2, 4, 7, 8]
Tensor
    [0, 0, 1, 1, 2, 2, 3, 3, 4]

Example 2: In this example axis parameter has been used. For creating an input tensor, we are utilizing the .tensor2d() method and in order to print the output we are using the .print() method.

Javascript




// Importing the tensorflow.js library 
import * as tf from "@tensorflow/tfjs"
  
// Defining tensor input elements 
const a = tf.tensor2d([[0, 0, 0], [2, 0, 0], [2, 0, 0]]);
  
// Calling the unique() method 
const {values, indices} = tf.unique(a, 0)
  
// Printing the values and indices
values.print();   // [[1, 0, 0],
                  //  [2, 0, 0]]
indices.print();  // [0, 0, 1]


 Output:

Tensor
    [[0, 0, 0],
     [2, 0, 0]]
Tensor
    [0, 1, 1]

Reference: https://js.tensorflow.org/api/latest/#unique



Last Updated : 30 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads