Open In App

Tensorflow.js tf.layers.embedding() Function

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

The tf.layers.embedding() function is used to map positive integers into dense vectors of fixed size.



Syntax:

tf.layers.embedding(args)

Parameters: This function accepts the args as a parameter which can have the following properties:



Return value: It returns the Embedding.

Example 1:




// Import library
import * as tf from "@tensorflow/tfjs"
    
// Create embedding layer
const embeddingLayer = tf.layers.embedding({
   inputDim: 10,
   outputDim: 3,
  inputLength: 2
});
  
const input = tf.ones([2, 2]);
  
// Apply embedding to input 
const output = embeddingLayer.apply(input);
    
// Print the output
console.log(output)

Output:

Tensor
    [[[0.0179072, 0.0069226, 0.0202718],
      [0.0179072, 0.0069226, 0.0202718]],

     [[0.0179072, 0.0069226, 0.0202718],
      [0.0179072, 0.0069226, 0.0202718]]]

Example 2:




// Import the library
import * as tf from "@tensorflow/tfjs"
    
// Create embedding layer
const embeddingLayer = tf.layers.embedding({
   inputDim: 100,
   outputDim: 4,
  inputLength: 3
});
    
const input = tf.ones([3, 3]);
  
// Apply embedding to input
const output = embeddingLayer.apply(input);
    
// Print the output
console.log(output)

Output:

Tensor
    [[[0.0443502, -0.0342815, 0.0228792, 0.0198386],
      [0.0443502, -0.0342815, 0.0228792, 0.0198386],
      [0.0443502, -0.0342815, 0.0228792, 0.0198386]],

     [[0.0443502, -0.0342815, 0.0228792, 0.0198386],
      [0.0443502, -0.0342815, 0.0228792, 0.0198386],
      [0.0443502, -0.0342815, 0.0228792, 0.0198386]],

     [[0.0443502, -0.0342815, 0.0228792, 0.0198386],
      [0.0443502, -0.0342815, 0.0228792, 0.0198386],
      [0.0443502, -0.0342815, 0.0228792, 0.0198386]]]

Reference: https://js.tensorflow.org/api/latest/#layers.embedding


Article Tags :