Open In App

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:



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

Example 1: Filling the tensor with a scalar number




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




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


Article Tags :