Open In App

Tensorflow.js tf.oneHot() Function

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:



Return: It returns a tf.Tensor.

Example 1:




// 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:




// 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
 

Article Tags :