1

I have a tensor with this size

torch.Size([128, 64])

how do I add one "dummy" dimension such as

torch.Size([1, 128, 64])
2
  • 2
    torch.unsqueeze Commented Jul 20, 2021 at 13:07
  • 2
    using torch.unsqueeze(0)along the first dimension. Commented Jul 20, 2021 at 13:28

1 Answer 1

3

There are several ways:

torch.unsqueeze:

torch.unsqueeze(x, 0)

Using None (or np.newaxis):

x[None, ...]
# or
x[np.newaxis, ...]

reshape or view:

x.reshape(1, *x.shape)
# or
x.view(1, *x.shape)
Sign up to request clarification or add additional context in comments.

3 Comments

Or x[None] ;)
Do not use x[None] or x[None,...]! Use x[np.newaxis] or x[np.newaxis, ...] ("Explicit is better than implicit.")
@GeorgeOgden you are right about np.newaxis. Nevertheless, I like it better to use just None. Moreover, in some cases, I do not need/want to explicitly import numpy in my code.

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.