在 Pytorch 中将 3D 张量转换为 4D 张量

bat*_*man 0 pytorch

我很难找到有关在 PyTorch 中重塑的信息。Tensorflow 非常简单。

我的张量有 shape torch.Size([3, 480, 480])。我想将其转换为形状为 [1,3,480,480] 的 4D 张量。我怎么做?

Jos*_*rty 7

您可以使用 unsqueeze()

例如:

x = torch.zeros((4,4,4))   # Create 3D tensor 
x = x.unsqueeze(0)         # Add dimension as the first axis (1,4,4,4)
Run Code Online (Sandbox Code Playgroud)

我见过一些人也使用索引None来添加单一维度。例如:

x = torch.zeros((4,4,4))   # Create 3D tensor 
print(x[None].shape)       #  (1,4,4,4)
print(x[:,None,:,:].shape) #  (4,1,4,4)
print(x[:,:,None,:].shape) #  (4,4,1,4)
print(x[:,:,:,None].shape) #  (4,4,4,1)
Run Code Online (Sandbox Code Playgroud)

就我个人而言,我更喜欢unsqueeze(),但熟悉两者也很好。