使用 unsqueeze
>>> help(torch.squeeze)
Help on built-in function unsqueeze:
unsqueeze(...)
unsqueeze(input, dim, out=None) -> Tensor
Returns a new tensor with a dimension of size one inserted at the
specified position.
The returned tensor shares the same underlying data with this tensor.
A :attr:`dim` value within the range ``[-input.dim() - 1, input.dim() + 1)``
can be used. Negative :attr:`dim` will correspond to :meth:`unsqueeze`
applied at :attr:`dim` = ``dim + input.dim() + 1``.
Args:
input (Tensor): the input tensor
dim (int): the index at which to insert the singleton dimension
out (Tensor, optional): the output tensor
Example::
>>> 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]])
也可以直接:
>>> a = torch.Tensor([1,2,3,4])
>>> a.unsqueeze(0)
tensor([[1., 2., 3., 4.]])