PyTorch torch.flatten function
PyTorch torch reference manual
torch.flatten is a PyTorch function for flattening a tensor.
Function definition
torch.flatten(input, start_dim, end_dim, out)
Usage examples
Example
import
torch
x
=
torch.
randn
(
2
,
3
,
4
)
Flatten to one dimension
y
=
torch.
flatten
(
x
)
(
"Original shape:"
,
x.
shape
)
(
"After flattening:"
,
y.
shape
)
Flatten from a specified dimension
z
=
torch.
flatten
(
x
,
start_dim
=
1
)
(
"Flatten from dim=1:"
,
z.
shape
)
The output is:
原始形状: torch.Size([2, 3, 4])
展平后: torch.Size([24])
从 dim=1 展平: torch.Size([2, 12])