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

时间:2019-10-09 02:44:17

标签: pytorch

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

我的张量的形状为distance > 0.05。 我想将其转换为形状为[1,3,480,480]的4D张量。 我该怎么办?

1 个答案:

答案 0 :(得分:2)

您可以使用unsqueeze()

例如:

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

我已经看到一些人在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)

我个人更喜欢unsqueeze(),但是对两者都熟悉是很好的。

相关问题