Tensorflow.js tf.fill() Function
Last Updated :
02 Jun, 2021
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