NumPy Tile: Understanding np.tile()

Ben Cook • Posted 2021-01-02 • Last updated 2021-10-15

np.tile() repeats an “array-like” input (called A in the docs) reps times:

import numpy as np

np.tile([1, 2], reps=(2, 3))

# Expected result
# array([[1, 2, 1, 2, 1, 2],
#        [1, 2, 1, 2, 1, 2]])

The tile operation works backwards through the reps argument. So in the above example, [1, 2] is repeated three times (the last element in reps) along the column axis and then two times (the first element in reps) along the row axis, making the output shape (2, 6).

Notice this is a higher rank than the input. NumPy uses a process similar to broadcasting rules to add dimensions when necessary. Because NumPy can add dimensions, you can pass a scalar in for the input argument A or the reps argument:

np.tile(1, (2, 2))

# Expected result
# array([[1, 1],
#        [1, 1]])

np.tile(np.eye(2), 2)

# Expected result
# array([[1., 0., 1., 0.],
#        [0., 1., 0., 1.]])

Another note: np.tile() is not the same as np.repeat(), which repeats each element of an array:

np.repeat([1, 2, 3, 4], 2)

# Expected result
# array([1, 1, 2, 2, 3, 3, 4, 4])

See the NumPy API docs for more information.

Finally, if you use machine learning frameworks, watch out! This is not how the tile() operation works in TensorFlow (no new dimensions get added) or PyTorch (no top-level function).