How can I use Torch to make make 3, 3 shape tensor a 3, 1, 3 shaped tensor only in Torch?

Viewed 22

If there is a Torch tensor of 3 x 3 how can I use Torch only to convert it to a 3 x 1 x 3 tensor?

Starting with this 3x3 tensor...

tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])

... That I want to convert to this 3x1x3 tensor

tensor([[[1., 1., 1.]],

        [[1., 1., 1.]],

        [[1., 1., 1.]]])

How can I do this in Torch? I know it can by done by indexing like so...
torch.ones(3, 3)[:, None, :] but I need to do this in Torch and Torch alone.

I tried with this line...

torch.ones(3, 3).unsqueeze(-1)

But it gave me

tensor([[[1.],
         [1.],
         [1.]],

        [[1.],
         [1.],
         [1.]],

        [[1.],
         [1.],
         [1.]]])

Which doesn't do the trick.

(The reason I can't do torch.ones(3, 3)[:, None, :] is that I'm using LibTorch in C++, and this type of indexing is not possible, but we can leave LibTorch and C++ out of it and just focus on if Torch can do this.)

1 Answers

Consider the (3,3) tensor x = torch.ones((3,3)). To reshape this to a (3,1,3) tensor, use x.unsqueeze(1).

Related