Open In App

Tensorflow.js tf.eye() Function

Tensorflow.js is an open-source library for creating machine learning models in Javascript that allows users to run the models directly in the browser.

The tf.eye() is a function defined in the class tf.Tensor. It’s used to create an identity matrix of specified rows and columns.



An identity matrix of shape [m, n] consists of value one at all diagonal elements and zero at remaining places.

Syntax:



tf.eye(numRows, numColumns, batchShape, dtype)

Parameters:

Return value : It returns a tensor of identity matrix.

Example 1: Creating an identity matrix of square shape




// Dynamic loading the "@tensorflow/tfjs" module
const tf = require('@tensorflow/tfjs');
require('@tensorflow/tfjs-node');
 
// Creating an identity matrix  of shape [3,3]
var matrix = tf.eye(numRows = 3)
   
// Printing the identity matrix
matrix.print()

Output :

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

Example 2: Creating an identity matrix of rectangular shape




// Dynamic loading the "@tensorflow/tfjs" module
const tf = require('@tensorflow/tfjs');
require('@tensorflow/tfjs-node');
 
// Creating an identity matrix  of shape [3,4]
var matrix = tf.eye(numRows = 3, numColumns = 4)
   
// Printing the identity matrix
matrix.print()

Output :

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

Example 3: Creating an identity matrix by specifying batchShape




// Dynamic loading the "@tensorflow/tfjs" module
const tf = require('@tensorflow/tfjs');
require('@tensorflow/tfjs-node');
 
// Creating an identity matrix  of shape [2,3]
// And include batchShape = [3] to replicate identity matrix 3 times
// Shape of returning tensor is [3, 2, 3]
var matrix = tf.eye(numRows = 2, numColumns = 3, batchShape = [3])
   
// Printing the identity matrix
matrix.print()

Output :

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

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

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

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


Article Tags :