0

I have a tensor of size (2, b, h) and I want to change it to the following size: (b, 2*h), where the corresponding lists are concatenated, for example:

a = torch.tensor([[[1, 2, 3], [4, 5, 6], [4, 4, 4]],
                  [[4, 5, 6], [7, 8, 9], [5, 5, 5]]])

I want:

b = tensor([[1, 2, 3, 4, 5, 6],
            [4, 5, 6, 7, 8, 9],
            [4, 4, 4, 5, 5, 5]])

2 Answers 2

2

Use permute first to change order of dimensions, then contiguous to prevent strides within the permuted tensor and finally use view to reshape the tensor.

b = a.permute(1,0,2).contiguous().view(a.shape[1],-1)
Sign up to request clarification or add additional context in comments.

Comments

0

In order to concatenate tensors in pytorch, you can use the torch.cat function which concatenates tensors along a chosen axis. In this example, you can do:

a = torch.tensor([[[1, 2, 3], [4, 5, 6], [4, 4, 4]],
                  [[4, 5, 6], [7, 8, 9], [5, 5, 5]]])

b = torch.cat((a[0], a[1]), dim=1)

Out:
tensor([[1, 2, 3, 4, 5, 6],
        [4, 5, 6, 7, 8, 9],
        [4, 4, 4, 5, 5, 5]])

1 Comment

Also doable. Might be harder to follow for the general case though. Furthermore, might be a bit slower than my proposition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.