The TensorFlow.js – tf.fill() Method
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:
It takes three parameters.
Parameters:
-
- 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.
- The value is the numeric or string element that is filled in a tensor.
- The dtype is used to specify the element type.
Example 1
Create a 1D tensor with numeric value -2 ,10 times in a tensor.
<!-- 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)
//actual 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.
<!-- 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')
//actual 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().
<!-- 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)
//actual 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: linuxhint.com