# Understand TensorFlow tf.tile(): Expand and Copy a Tensor – TensorFlow Tutorial

By | June 30, 2021

In order to repeat data to expand a tensor, we can use tf.tile() function. In this tutorial, we will use some examples to show you how to this function correctly.

## Syntax

tf.tile(
input,
multiples,
name=None
)

Constructs a tensor by tiling a given tensor.

Parameters

input: a tensor to be tiled

multiples: must be 1-D. D must be the same as the number of dimensions in input. It determines how to tile input.

We will write some examples to illustrate how to tile a tensor.

## Expand a tensor by its axis

Here we will create 2 dimensions tensor to expand.

import tensorflow as tf
import numpy as np

xs = tf.Variable(np.array([[1, 3, 2, 1],[2, 2, 5, 4]]), dtype = tf.float32)
xy = tf.tile(xs, multiples = [2, 3])

Here the shape of xs is (2, 4). The dimension of xs is 2, which means the length of multiples is 2.

In this tutorial, we set multiples = [2, 3], which means we will repeat data on axis = 0 two times in xs, repeat data on axis = 1 three times in xs.

Output xy, we will get the result.

init = tf.global_variables_initializer()
init_local = tf.local_variables_initializer()
with tf.Session() as sess:
sess.run([init, init_local])
print(sess.run(xy))

The xy is:

From the result, we can find the dimension of xy is the same to xs.

## How about multiples = [1, 3]

It means we will repeat the data one times on axis =0 in xs, which means the data on axis = 0 is not changed. The xy will be:

[[1. 3. 2. 1. 1. 3. 2. 1. 1. 3. 2. 1.]
[2. 2. 5. 4. 2. 2. 5. 4. 2. 2. 5. 4.]]

## Repeat elements one by one

If you want to repeat elements in xs one by one, you can do like this:

xs = tf.reshape(xs, [2, 4, 1])
xy = tf.tile(xs, multiples = [1, 1, 3])

xy = tf.reshape(xs, [2, 12])

The xy will be:

[[1. 1. 1. 3. 3. 3. 2. 2. 2. 1. 1. 1.]
[2. 2. 2. 2. 2. 2. 5. 5. 5. 4. 4. 4.]]