PyTorch torch.reshape function
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:
input(Tensor): the input tensor.shape(tuple or int): target shape. The number of elements in the shape must be the same as the number of elements in the input tensor. You can use-1to let PyTorch automatically infer the dimension.
Return Value:
torch.Tensor: return a reshaped view of the tensor.
Usage examples
Example 1: reshape a one-dimensional tensor into two dimensions
Example
import
torch
Create a 1D tensor
x
=
torch.
arange
(
12
)
(
"Original shape:"
,
x.
shape
)
(
x
)
Change to a 3x4 two-dimensional tensor
y
=
torch.
reshape
(
x
,
(
3
,
4
)
)
(
"New shape:"
,
y.
shape
)
(
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
)
(
"Original shape:"
,
x.
shape
)
Use -1 to automatically infer the last dimension
y
=
torch.
reshape
(
x
,
(
2
,
1
)
)
(
"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
(
"Original shape:"
,
x.
shape
)
Flatten to (batch size, others)
y
=
torch.
reshape
(
x
,
(
32
,
1
)
)
(
"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
)
)
(
"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
torch.reshapeThe returned tensor may be a view of the original data or a copy, depending on the memory layout.- If you need to guarantee a view is returned, you can use
tensor.view(), but make sure the tensor is contiguous. - The total number of elements in the shape must be the same as the number of elements in the original tensor.