Fill a tensor with default value N times

Hi!

I have a tensor of shape torch.Size([2, 3]) with this content

tensor([[ 1.0000,  0.5000,  0.0000],
        [ 0.5000,  1.0000,  0.0000]])

I want to repeat the values 32 times and get a tensor with a shape torch.Size([32, 2, 3]) like that

tensor([[[ 1.0000,  0.5000,  0.0000],
        [ 0.5000,  1.0000,  0.0000]],
        [[ 1.0000,  0.5000,  0.0000],
        [ 0.5000,  1.0000,  0.0000]],
        ..........
       [[ 1.0000,  0.5000,  0.0000],
        [ 0.5000,  1.0000,  0.0000]]]
)

I tried

identity = [[1, 0.5, 0], [0.5, 1, 0]]
theta = torch.ones((32,), dtype=torch.float32)
theta = theta.new_tensor(identity)
theta = theta.view(32, theta.size(0), theta.size(1))

But it’s not working.
Please kindly help!!!

Lucky enough, I tried

theta = theta.new_tensor(32 * identity)
theta = theta.view(b, 2, 3)

and it works. Don’t know if it’s the right answer

This should work:

x = torch.tensor([[ 1.0000,  0.5000,  0.0000],
                  [ 0.5000,  1.0000,  0.0000]])
    
y = x.unsqueeze(0).repeat(32, 1, 1) # copies the data
z = x.unsqueeze(0).expand(32, -1, -1) # returns view

Note, that .expand returns a view and sets th stride for the expanded dimension to 0, while .repeat copies the data.

1 Like

Thanks, I’ll do it that way.