pytorch张量进行尺寸扩展

问题描述

使用pytorch张量进行维扩展的方式是什么?

-之前: torch.Size([3,3,3])

tensor([[[ 0.,1.,2.],[ 3.,4.,5.],[ 6.,7.,8.]],[[ 9.,10.,11.],[12.,13.,14.],[15.,16.,17.]],[[18.,19.,20.],[21.,22.,23.],[24.,25.,26.]]],device='cuda:0',dtype=torch.float64)

-之后: torch.Size([2,3,3,3])

tensor([[[[ 0.,[[[0.,26.]]]],dtype=torch.float64)

在numpy下会像这样工作:

b =  np.broadcast_to(a1[None,:,:],(2,3,3))

在pytorch下如何工作?我想利用GPU。预先感谢您的帮助!

解决方法

可以在新维度上添加unsqeeze(下面用0指定第一个维度,即位置0),然后沿该维度重复两次数据(和一次,即在其他维度上没有重复。

before = torch.tensor(...,dtype=torch.float64,device='cuda:0')
after = before.unsqueeze(0).repeat(2,1,1)
,

对于您给定的预期结果,我们可以使用torch.Tensor.expand

b = a1.expand([2,3,3])