Tensorflow.js tf.initializers.identity() 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 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.
Syntax:
tf.initializers.identity(Gain)
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.
Javascript
// Importing the tensorflow.Js libraryimport * as tf from "@tensorflow/tfjs"Â
// Generates the identity matrixconst value=tf.initializers.identity(1.0)Â
// Print gainconsole.log(value) |
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.
Javascript
// Importing the tensorflow.Js libraryimport * as tf from "@tensorflow/tfjs"Â
// Define the inputconst inp = tf.input({shape:[4]});Â
// Create identity matrix with gain 1const value=tf.initializers.identity(1.0)Â
Â
// Dense layer 1const denseLayer1 = tf.layers.dense({    units: 6,     activation: 'relu',    kernelInitialize: value});Â
// Dense layer 2const denseLayer2 = tf.layers.dense({Â Â Â Â units: 8, Â Â Â Â activation: 'softmax'});Â
const out = denseLayer2.apply(denseLayer1.apply(inp));Â
//Â Model creationconst model = tf.model({inputs:inp,outputs:out});Â
// Make predictionconsole.log("Lets Make Some Prediction :")model.predict(tf.ones([2, 4])).print(); |
Output :
Lets Make Some Prediction :
Tensor
[[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]]
Reference: Â https://js.tensorflow.org/api/3.6.0/#initializers.identity



