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

PyTorch torch.reshape function

PyTorch torch.reshape function


PyTorch torch reference manual PyTorch torch reference manual

torch.reshape is a function in PyTorch used to change the shape of a tensor. It returns a new tensor with the same number of elements as the original, but with a different shape.

This is a very common operation in deep learning, used to adjust the data shape to meet the input requirements of different layers.

Function definition

torch.reshape(input, shape)

Parameters:

Return Value:


Usage examples

Example 1: reshape a one-dimensional tensor into two dimensions

Example

import

torch

Create a 1D tensor

x

=

torch.

arange

(

12

)

print

(

"Original shape:"

,

x.

shape

)

print

(

x

)

Change to a 3x4 two-dimensional tensor

y

=

torch.

reshape

(

x

,

(

3

,

4

)

)

print

(

"New shape:"

,

y.

shape

)

print

(

y

)

The output is:

原始形状: torch.Size([12])

tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

新形状: torch.Size([3, 4])

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

        [ 4,  5,  6,  7],

        [ 8,  9, 10, 11]])

Example 2: use -1 to automatically infer the dimension

Example

import

torch

Create a 3D tensor

x

=

torch.

randn

(

2

,

3

,

4

)

print

(

"Original shape:"

,

x.

shape

)

Use -1 to automatically infer the last dimension

y

=

torch.

reshape

(

x

,

(

2

,

1

)

)

print

(

"New shape:"

,

y.

shape

)

The output is:

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

新形状: torch.Size([2, 12])

Example 3: flatten into two dimensions

Example

import

torch

Create a four-dimensional tensor (typical batched image data)

x

=

torch.

randn

(

32

,

3

,

224

,

224

)

 

Batch size 32, channels 3, height and width 224

print

(

"Original shape:"

,

x.

shape

)

Flatten to (batch size, others)

y

=

torch.

reshape

(

x

,

(

32

,

1

)

)

print

(

"Flattened shape:"

,

y.

shape

)

The output is:

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

展平后形状: torch.Size([32, 150528])

This is often used before feeding image data into a fully connected layer.

Example 4: the difference between reshape and view

Example

import

torch

Create a contiguous tensor

x

=

torch.

arange

(

12

)

.

reshape

(

3

,

4

)

reshape may return a view or a copy

y

=

torch.

reshape

(

x

,

(

4

,

3

)

)

print

(

"y is a view of x:"

,

y.

is_contiguous

(

)

or

y.

data_ptr

(

)

==

x.

data_ptr

(

)

)

torch.reshape can handle non-contiguous tensors, while tensor.view() requires the tensor to be contiguous.


Notes


PyTorch torch reference manual PyTorch torch reference manual