Search code examples
luatorch

How to expand dims in Torch (add dimension to tensor)


I want to add dimensions to tensor, as in numpy.expand_dims. How can I do it?

I can do it with following code:

a = torch.Tensor({{1,2}, {3,4}, {5,6}}) --array with shape (3,2)
a_size_table = a:size():totable()
table.insert(a_size_table, 1, 1)  -- adding `1` before first dimension
a:reshape(torch.LongStorage(a_size_table)) -- returning array with shape (1,3,2)

It seems too complicated to me (compare it to np.expand_dims(a,0)). May be there is a better way to do it?


Solution

  • There is nn.utils.addSingletonDimension. I have found answer here https://www.bountysource.com/issues/38773074-convenience-function-to-add-a-singleton-dimension-to-a-torch-tensor