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

PyTorch torch.unflatten function

PyTorch torch.unflatten function


PyTorch torch reference manual PyTorch torch reference manual

torch.unflatten is a function in PyTorch used to expand dimensions. It expands an existing dimension of a tensor into multiple dimensions, used to reshape the tensor.

Function definition

torch.unflatten(input, dim, sizes)

Parameter Description:


Usage examples

Example

import

torch

Create a 1D tensor

x

=

torch.

arange

(

12

)

Expand into a 3x4 matrix

y

=

torch.

unflatten

(

x

,

dim

=

0

,

sizes

=

(

3

,

4

)

)

print

(

y.

shape

)

print

(

y

)

The output is:

torch.Size([3, 4])

tensor([[ 0,  1,  2,  3],

        [ 4,  5,  6,  7],

        [ 8,  9, 10, 11]])

Example

import

torch

Create a flattened tensor

x

=

torch.

randn

(

24

)

Expand into a 2x3x4 three-dimensional tensor

y

=

torch.

unflatten

(

x

,

dim

=

0

,

sizes

=

(

2

,

3

,

4

)

)

print

(

y.

shape

)

The output is:

torch.Size([2, 3, 4])

Example

import

torch

Create a flattened tensor

x

=

torch.

randn

(

12

)

Dimensions can be specified by name

x

=

x.

rename

(

'N'

)

y

=

torch.

unflatten

(

x

,

dim

=

'N'

,

sizes

=

(

3

,

4

)

)

print

(

y.

shape

)

The output is:

torch.Size([3, 4])


PyTorch torch reference manual PyTorch torch reference manual