Thursday, October 23, 2025
HomeLanguagesJavascriptTensorflow.js tf.zeros() Function

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:

  • shape: It takes the shape of the tensor we are going to generate.
  • dataType: It is the type of tensor in the resulting element. It can be a ‘float32′, ‘int32′ or ‘bool’. It defaults to the “float32” value. It is an optional parameter.

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().

Javascript




// 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.

Javascript




// 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().

Javascript




// 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
 

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS