Skip to content
Related Articles

Related Articles

Improve Article

Tensorflow.js tf.zeros() Function

  • Last Updated : 04 Jul, 2021
Geek Week

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
 

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :