Unsqueeze the data from one dimension to three dimension

In below code i have to use “unsqueeze” 2 times for 3d conversion. Is there anyway to convert 1d to 3d using “unsqueeze” single time.

from torchvision import transforms
a=torch.ones([5],requires_grad=True) * - 0.5
a=a.unsqueeze_(0)
a=a.unsqueeze_(0)
print(a.shape)

You could index the tensor with None to add additional dimensions:

x = torch.randn(10)
y = x[None, :, None, None]
print(y.shape)
> torch.Size([1, 10, 1, 1])
1 Like