Thursday, September 4, 2025
HomeLanguagesJavascriptTensorflow.js tf.fill() Function

Tensorflow.js tf.fill() 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.fill() is a function defined in the class tf.Tensor. It is used to create a tensor that is filled with a scalar value.

Syntax:

tf.fill( shape, value, dtype )

Parameters:

  • shape: It’s an array of integers defining the shape of the output tensor.
  • value: It’s a scalar value with which the output tensor is to be filled.
  • dtype: It defines the data type of elements in the output tensor. It can be ‘float32’|’int32’|’bool’|’complex64’|’string’. It’s optional to include and default value is ‘float32’.

Return value: It returns the tensor of a specified shape filled with a scalar value.

Example 1: Filling the tensor with a scalar number

  • Creating a tensor of shape [4, 2] filled with scalar value 2.
  • It takes the default datatype of elements in the output tensor as float.

Javascript




// Dynamic loading the "@tensorflow/tfjs" module
const tf = require('@tensorflow/tfjs');
require('@tensorflow/tfjs-node');
  
// Creating a tensor of of shape [4,2] filled with 
// scalar value 2
var matrix = tf.fill(shape = [4,2],value = 2)
    
// Printing the tensor
matrix.print()


Output:

Tensor
    [[2, 2],
     [2, 2],
     [2, 2],
     [2, 2]]

Example 2: Explicitly defining the data type of elements

  • Create a tensor of shape [3, 4] filled with string ‘Gfg’. 

Javascript




// Dynamic loading the "@tensorflow/tfjs" module
const tf = require('@tensorflow/tfjs');
require('@tensorflow/tfjs-node');
  
// Creating a tensor  of shape [3,4] filled
// with string value 'Gfg'
var matrix = tf.fill(shape = [3, 4], 
        value = 'Gfg', dtype = 'string')
    
// Printing the tensor
matrix.print()


Output:

Tensor
    [['Gfg', 'Gfg', 'Gfg', 'Gfg'],
     ['Gfg', 'Gfg', 'Gfg', 'Gfg'],
     ['Gfg', 'Gfg', 'Gfg', 'Gfg']]

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6746 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS