Open In App

Tensorflow.js tf.zeros() 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.zeros() function is used to create a new tensor with all elements set to zero.



Syntax:

tf.zeros(shape, dataType)

Parameters:



Return Value: It returns the tensor of the given shape with all elements set to zero.

Example 1: In this example, we are creating a tensor of shape 1*1 using tf.zeros().




// Importing the tensorflow.Js library
import * as tf from "@tensorflow/tfjs"
 
// Creating a shape variable
// which stores the shape
var shape = [1,1]
 
// Creating the tensor
var val = tf.zeros(shape)
 
// Printing the tensor
val.print()

Output: 

Tensor
     [[0],]

 

Example 2: In this example, we are creating a tensor of shape 2*2 using tf.zeros() and with dataType parameter.




// Importing the tensorflow.Js library
import * as tf from "@tensorflow/tfjs"
 
// Creating a shape variable
// which stores the shape
var shape = [2, 2]
 
// Creating a d_Type variable
// which stores the data-type
var d_Type = 'bool'
 
// Creating the tensor
var val = tf.zeros(shape, d_Type)
 
// Printing the tensor
val.print()

 
Output: 

Tensor
    [[false, false],
     [false, false]]

 

Example 3: In this example, we are creating a tensor of shape 1*1 using tf.zeros().




// Importing the tensorflow.Js library
import * as tf from "@tensorflow/tfjs"
 
// Creating a shape variable
// which stores the shape
var shape = [3,3]
 
// Creating the tensor
var val = tf.zeros(shape)
 
// Printing the tensor
val.print()

 
Output: 

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

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


Article Tags :