Open In App

Tensorflow.js tf.oneHot() Function

Improve
Improve
Like Article
Like
Save
Share
Report

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

The tf.oneHot() function is used to create a one-hot tf.Tensor. The locations represented by indices take the value as 1 (default value) also known as onValue, while all other locations take the value as 0( default Value) also known as offValue.

Syntax:

tf.oneHot (indices, depth, onValue, offValue)

Parameter: This function accepts three parameters which are illustrated below:

  • indices It can tf.Tensor(TypedArray or Array) of indices with dtype int32.
  • depth The datatype of depth is number. It is used to represent the depth of the one hot dimension.
  • onValue The datatype of onValue is number. It is used to fill in the output when the index matches the location. It is an optional argument.
  • offValue The datatype of offValue is number. It is used to fill in the output when the index does not match the location. It is also an optional argument.

Return: It returns a tf.Tensor.

Example 1:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
 
// Use of oneHot function.
var val = tf.oneHot(tf.tensor1d([0,1,2], 'int32'), 3);;
 
// Printing the tensor
val.print()


Output:

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

Example 2:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
 
 
// Creating and initializing a new variable
var val = tf.oneHot(tf.tensor1d([0,1,2], 'int32'), 3,9,-1);
 
// Printing the tensor
val.print()


Output:

Tensor
    [[9 , -1, -1],
    [-1, 9 , -1],
    [-1, -1, 9 ]]

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


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