Open In App
Related Articles

Tensorflow.js tf.initializers.identity() Function

Improve Article
Save Article
Like Article

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 Initializer class is the base class of all initializers in Tensorflow.js. The initializers are used to initialize the Tensors with the specific values. It returns the tensor object initialized as specifies by the initializer. So in this article, we are going to see how identity initializer works. This is the initializer that initialized a new tensor object with an identity matrix. It only used for 2D matrices.



Parameter :

  • Gain: It is the multiplication factor that applies to the identity matrix.

Return Value: It returns tf.initializers.Initializer

Example 1: In this example, we are going to check the standalone use of the identity() function.


// Importing the tensorflow.Js library
import * as tf from "@tensorflow/tfjs"
// Generates the identity matrix
const value=tf.initializers.identity(1.0)
// Print gain

Output :

 "gain": 1

Example 2: In this example, we are going to use an identity matrix with a dense layer using the identity() and dense() function.


// Importing the tensorflow.Js library
import * as tf from "@tensorflow/tfjs"
// Define the input
const inp = tf.input({shape:[4]});
// Create identity matrix with gain 1
const value=tf.initializers.identity(1.0)
// Dense layer 1
const denseLayer1 = tf.layers.dense({
    units: 6,
    activation: 'relu',
    kernelInitialize: value
// Dense layer 2
const denseLayer2 = tf.layers.dense({
    units: 8,
    activation: 'softmax'
const out = denseLayer2.apply(denseLayer1.apply(inp));
//  Model creation
const model = tf.model({inputs:inp,outputs:out});
// Make prediction
console.log("Lets Make Some Prediction :")
model.predict(tf.ones([2, 4])).print();

Output :

Lets Make Some Prediction :
   [[0.1651815, 0.1695402, 0.0670628, 0.0771763, 
     0.1045933, 0.1027268, 0.1647871, 0.148932],
    [0.1651815, 0.1695402, 0.0670628, 0.0771763, 
     0.1045933, 0.1027268, 0.1647871, 0.148932]]


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 21 Jul, 2021
Like Article
Save Article
Similar Reads
Complete Tutorials