Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.unsqueeze function

PyTorch torch.unsqueeze function


PyTorch torch reference manual PyTorch torch reference manual

torch.unsqueeze is a function in PyTorch used to insert a dimension of size 1 at a specified position.

Function definition

torch.unsqueeze(input, dim)


Usage examples

Example

import

torch

x

=

torch.

randn

(

2

,

3

)

print

(

"Original shape:"

,

x.

shape

)

Insert a dimension at dim=0

y

=

torch.

unsqueeze

(

x

,

dim

=

0

)

print

(

"After expanding dim=0:"

,

y.

shape

)

Insert a dimension at dim=1

z

=

torch.

unsqueeze

(

x

,

dim

=

1

)

print

(

"After expanding dim=1:"

,

z.

shape

)

The output is:

原始形状: torch.Size([2, 3])

dim=0 扩展后: torch.Size([1, 2, 3])

dim=1 扩展后: torch.Size([2, 1, 3])


PyTorch torch reference manual PyTorch torch reference manual