What does "unsqueeze" do in Pytorch?

StarckOverflar picture StarckOverflar · Jul 28, 2019 · Viewed 36.1k times · Source

I'm looking at the documentation, and here is their example. I cannot understand how this example corresponds to their explanation: "Returns a new tensor with a dimension of size one inserted at the specified position."

>>> x = torch.tensor([1, 2, 3, 4])
>>> torch.unsqueeze(x, 0)
tensor([[ 1,  2,  3,  4]])
>>> torch.unsqueeze(x, 1)
tensor([[ 1],
        [ 2],
        [ 3],
        [ 4]])

Answer

norok2 picture norok2 · Jul 28, 2019

If you look at the shape of the array before and after, you see that before it was (4,) and after it is (1, 4) (when second parameter is 0) and (4, 1) (when second parameter is 1). So a 1 was inserted in the shape of the array at axis 0 or 1, depending on the value of the second parameter.

That is opposite of np.squeeze() (nomenclature borrowed from MATLAB) which removes axes of size 1 (singletons).