如何在Torch中扩展dims(向张量添加维度)

我想向张量添加维度,就像 numpy.expand_dims 那样。我该怎么做?

我可以使用以下代码实现:

a = torch.Tensor({{1,2}, {3,4}, {5,6}}) --shape (3,2)
a_size_table = a:size():totable()
table.insert(a_size_table, 1, 1)  -- 在第一维之前添加`1`
a:reshape(torch.LongStorage(a_size_table)) -- 返回形状为 (1,3,2) 的张量

这对我来说似乎太麻烦了(与 np.expand_dims(a,0) 相比)。也许有更好的方法?

点赞
用户4744283
用户4744283

有一个 nn.utils.addSingletonDimension 函数,我在这里找到了答案:https://www.bountysource.com/issues/38773074-convenience-function-to-add-a-singleton-dimension-to-a-torch-tensor

2016-11-29 01:37:11