Confused about repeat. How to repeat columns?


I have an 1D tensor, for example:

t = torch.rand(4)

What I want to do is simply repeat it by the second dimensions for a few times. Which means:




0.1  0.1  0.1
0.3  0.3  0.3
0.2  0.2  0.2 
0.9  0.9  0.9

The obvious choice would be repeat. So I have a one dimensional tensor which is basically a column. I want to repeat that column three times on the second dimension (and one times on the first dimension), so I write:

tr = t.repeat(1, 3)

I get a tensor of size 1x9.

I simply don’t get the logic behind this. For achieve that I want I have to write:

tr = t.repeat(3, 1).t()

It looks like first dimension is somehow transposed to the second when doing repeat, which is kinda confusing. Is it the intended behavior?

1 Like

Hi @unbornchikken,

Here’s what you’re looking for:

t = torch.rand(4,1)
print t
tr = t.repeat(1, 3)
print tr

You need the original tensor to be an Nx1 tensor (a 2D tensor, with one of those dimensions just with 1 element) rather than a N-element vector.

If you have a vector to start with, just unsqueeze it:

t = torch.rand(4).unsqueeze(1)
print t
tr = t.repeat(1, 3)
print tr

@Pete_Florence thanks. I was looking for a top level function like numpy.repeat and trying torch.repeat but it doesn’t exist

repeat is a torch.tensor method, so you should call it using a tensor:

x = torch.randn(1, 1)
x.repeat(2, 1)

I think einops notation is less confusing. You can directly repeat along new axis

einops.repeat(x, 'i -> i newaxis', newaxis=3) # make 3 identical columns
einops.repeat(x, 'i -> newaxis i', newaxis=3) # make 3 identical rows