JavaScript

The Tf.Tile() Function in TensorFlow.Js

In the TensorFlow.js library, the tf.tile() function is used to create a new tensor by duplicating the elements in the existing tensor. It takes two parameters.

Syntax:

tf.tile(tensor,[n])

Parameters:

  1. The tensor is the input tensor with elements.
  2. The n is an integer in which the elements in a tensor are duplicated.

Example 1

Create a 1D tensor with 4 integers and duplicate 4 times using tf.tile().

<html>

<!--   CDN Link that delivers the Tensorflow.js framework -->

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>

<body>

<script>

//tensor

let tensor = tf.tensor1d([10,20,30,30]);

document.write("<b>Tensor:</b> ",tensor);

document.write("<br>");

//duplicate the elements 4 times in a tensor

document.write("<b>Duplicated Tensor: </b> "+tf.tile(tensor,[4]));

</script>

</body>

</html>

Output:

Elements in a tensor are duplicated 4 times.

Example 2

Create a 1D tensor with 2 integers and duplicate 2 times using tf.tile().

<html>

<!--   CDN Link that delivers the Tensorflow.js framework -->

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>

<body>

<script>

 

//tensor

let tensor = tf.tensor1d([45,67]);

document.write("<b>Tensor:</b> ",tensor);

document.write("<br>");

//duplicate the elements 2 times in a tensor

document.write("<b>Duplicated Tensor: </b> "+tf.tile(tensor,[2]));

</script>

</body>

</html>

Output:

Elements in a tensor are duplicated 2 times.

If you want to duplicate elements in a two-dimensional tensor, then you have to specify the duplicate values for the row and column.

Syntax:

tf.tile(tensor,[r,c])

r – duplicates the rows r times.

c – duplicates the elements in each row c times.

Example

Let’s create a two-dimensional tensor with 2 rows and 2 columns and duplicate the rows 2 times and each value in a row three times.

<html>

<!--   CDN Link that delivers the Tensorflow.js framework -->

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>

 

 

<body>

<script>

 

//tensor

let tensor = tf.tensor2d([45,67,1,2],[2,2]);

document.write("<b>Tensor:</b> ",tensor);

document.write("<br>");

//duplicate the elements in each row 2 times and each column 3 times

document.write("<b>Duplicated Tensor: </b> "+tf.tile(tensor,[2,3]));

</script>

</body>

</html>

Output:

 

We can see that the rows are duplicated two times, and, in each row, each value is duplicated three times.

Conclusion

This guide discussed how to duplicate elements in a tensor with the TensorFlow.js library. It takes an integer value that is used to duplicate the “n” number of times.

If you want to duplicate elements in a two-dimensional tensor, then you have to specify the duplicate values for the rows and columns.

About the author

Gottumukkala Sravan Kumar

B tech-hon's in Information Technology; Known programming languages - Python, R , PHP MySQL; Published 500+ articles on computer science domain