How to repeat tensor in a specific new dimension in PyTorch

Adding to the answer provided by @Alleo. You can use following Einops function.

einops.repeat(example_tensor, 'b h w -> (repeat b) h w', repeat=b)

Where b is the number of times you want your tensor to be repeated and h, w the additional dimensions to the tensor.

Example -

example_tensor.shape -> torch.Size([1, 40, 50]) 
repeated_tensor = einops.repeat(example_tensor, 'b h w -> (repeat b) h w', repeat=8)
repeated_tensor.shape -> torch.Size([8, 40, 50]) 

More examples here - https://einops.rocks/api/repeat/


Einops provides repeat function

import einops
einops.repeat(x, 'm n -> m k n', k=K)

repeat can add arbitrary number of axes in any order and reshuffle existing axes at the same time.


tensor.repeat should suit your needs but you need to insert a unitary dimension first. For this we could use either tensor.unsqueeze or tensor.reshape. Since unsqueeze is specifically defined to insert a unitary dimension we will use that.

B = A.unsqueeze(1).repeat(1, K, 1)

Code Description A.unsqueeze(1) turns A from an [M, N] to [M, 1, N] and .repeat(1, K, 1) repeats the tensor K times along the second dimension.

Tags:

Repeat

Pytorch