3

I have two tensors in PyTorch as:

a.shape, b.shape
# (torch.Size([512, 28, 2]), torch.Size([512, 28, 26]))

My goal is to join/merge/concatenate them together so that I get the shape: (512, 28, 28).

I tried:

torch.stack((a, b), dim = 2).shape
torch.cat((a, b)).shape

But none of them seem to work.

I am using PyTorch version: 1.11.0 and Python 3.9.

Help?

1
  • 3
    concatenated = torch.cat((a, b), 2) print(concatenated.shape) Should work. Commented May 18, 2022 at 14:54

1 Answer 1

3

Set dim parameter to 2 to concatenate over last dimension:

a = torch.randn(512, 28, 2)
b = torch.randn(512, 28, 26)

print(a.size(), b.size())

# set dim=2 to concat over 2nd dimension
c = torch.cat((a, b), dim=2)

print(c.size())
torch.Size([512, 28, 2]) torch.Size([512, 28, 26])
torch.Size([512, 28, 28])
Sign up to request clarification or add additional context in comments.

Comments

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.