The TensorFlow.js – tf.fill() Method


In Deep Learning, we have to fill the pixels of an image in an array or in a matrix. To accomplish this, TensorFlow.js supports the tf.fill() function. It is used to set the same value in the tensor array or tensor matrix.

tf.fill() Meethod

The tf.fill() function is used to set the element in a tensor with specified value.

We can fill that value more than one time in a tensor.

Syntax:

tf.fill(shape,value,dtype)

 
It takes three parameters.

Parameters:

    1. The shape is used to set the value n times. If it is a two-dimensional tensor, we can specify the number of rows and number of columns.
    2. The value is the numeric or string element that is filled in a tensor.
    3. The dtype is used to specify the element type.

Example 1

Create a 1D tensor with numeric value -2 ,10 times in a tensor.

<html>
<!—   CDN Link that delivers the Tensorflow.js framework —>
<script src=«https://cdn.jsdelivr.net/npm/@tensorflow/tfjs»></script>
 
<body>
<center><h1>Linux Hint</h1></center>
<center><h2>Tensorflow.js – tf.fill() </h2></center>
<script>
 //create a tensor with value-2 and fill 10 times.
let values = tf.fill(shape = [10],value = 2)
//contemporáneo tensor
document.write(«Tensor: «,values);
 
</script>
 
</body>
</html>

 
Output:


2 is added 10 times to a tensor.

Example 2

Create a 1D tensor with string value, ‘Linux Hint’, 4 times in a tensor.

<html>
<!—   CDN Link that delivers the Tensorflow.js framework —>
<script src=«https://cdn.jsdelivr.net/npm/@tensorflow/tfjs»></script>
 
<body>
<center><h1>Linux Hint</h1></center>
<center><h2>Tensorflow.js – tf.fill() </h2></center>
<script>
 //create a tensor with element-‘Linux Hint’ and fill 4 times.
let values = tf.fill(shape = [4],value=‘Linux Hint’,dtype=‘string’)
//contemporáneo tensor
document.write(«Tensor: «+values);
 
</script>
 
</body>
</html>

 
Output:


‘Linux Hint’ is added 4 times to a tensor with string data type.

Example 3

Create a 2D tensor with numeric value – 20, 6 (2 rows and 3 columns) times using tf.fill().

<html>
<!—   CDN Link that delivers the Tensorflow.js framework —>
<script src=«https://cdn.jsdelivr.net/npm/@tensorflow/tfjs»></script>
 
<body>
<center><h1>Linux Hint</h1></center>
<center><h2>Tensorflow.js – tf.fill() </h2></center>
<script>
 //create a tensor with element-‘Linux Hint’ and fill 5 times.
let values = tf.fill(shape = [2,3],value=20)
//contemporáneo tensor
document.write(«Tensor: «+values);
 
</script>
 
</body>
</html>

 
Output:


The value, 20, is added in tensor with shape 2 rows and 3 columns.

Conclusion

We saw how to fill values in a tensor using the fill() method. Using this method, we can specify the datatype of the element and we can create a tensor with multiple dimensions. This article discussed three different examples with string and integer data types.



Source link