Generalized unsqeeze to many dimensions

Hi,

Is there any function (or any simple way) to expand an $m$ dimensional tensor to $m + n$ dimensions?
Basically I want to achieve the following code,

foo = torch.ones((2,2))
bar = foo.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)

by something like

foo = torch.ones((2,2))
bar = foo.unsqueeze(-1,n=5)

by an imaginary overload of unsqueeze that inserts n new dimensions at the end of tensor foo.
So far the only solution I found was

bar = foo[(None,)*5].permute(-1,-2,0,1,2,3,4,5)

That is looks weird and I do not want to do the permute at the end also something cleaner would be nice.

Thanks

You can do something like this (it looks kind of messy though):

foo[(...,) + (1,) * n]

or you can use view/reshape (a bit cleaner):

foo.view(foo.shape + (1,) * n)
2 Likes