How to add a new dimension to a PyTorch tensor?

Viewed 13028

In NumPy, I would do

a = np.zeros((4, 5, 6))
a = a[:, :, np.newaxis, :]
assert a.shape == (4, 5, 1, 6)

How to do the same in PyTorch?

3 Answers
a = torch.zeros(4, 5, 6)
a = a[:, :, None, :]
assert a.shape == (4, 5, 1, 6)

You can add a new axis with torch.unsqueeze() (first argument being the index of the new axis):

>>> a = torch.zeros(4, 5, 6)
>>> a = a.unsqueeze(2)

>>> a.shape
torch.Size([4, 5, 1, 6])

Or using the in-place version: torch.unsqueeze_():

>>> a = torch.zeros(4, 5, 6)
>>> a.unsqueeze_(2)

>>> a.shape
torch.Size([4, 5, 1, 6])
Related