Bridge convolutional and linear layers
Convert image or feature-map tensors into vectors before fully connected layers.
PyTorch · Class
torch.nn.Flatten is a module that combines a contiguous range of dimensions into one. By default, it preserves dimension 0 and flattens dimensions 1 through the last dimension.
nn.Flatten combines one contiguous range of tensor dimensions into a single dimension. By default it starts at dimension 1 and continues through the last dimension, so a batch dimension remains separate; custom start_dim and end_dim select a different inclusive range.
class torch.nn.modules.flatten.Flatten(start_dim=1, end_dim=-1)| Name | Type | Description |
|---|---|---|
start_dim | int | First dimension to flatten; defaults to 1. |
end_dim | int | Last dimension to flatten; defaults to -1. |
A Tensor with the selected contiguous dimensions replaced by one dimension.
import torch
from torch import nn
x = torch.randn(32, 1, 5, 5)
layer = nn.Flatten()
y = layer(x)
print(y.shape) # torch.Size([32, 25])Flattens dimensions 1 through the final dimension while preserving the batch dimension.
Convert image or feature-map tensors into vectors before fully connected layers.
Add a reshape operation inside a layer pipeline without writing a custom module.
Flatten only selected middle dimensions while retaining leading or trailing structure.
nn.Flatten is a module that combines a contiguous range of dimensions into one dimension. Its defaults are start_dim=1 and end_dim=-1, which preserve the leading dimension and flatten the rest.
Follow-up: How does the output shape change? The selected dimensions are replaced by one dimension whose size is the product of their sizes.
start_dim identifies the first dimension included, and end_dim identifies the last one included. Both boundaries are part of the flattened range.
Follow-up: How would you flatten dimensions 0 through 2? Construct nn.Flatten(0, 2).
For an input shaped (32, 1, 5, 5), the default module produces shape (32, 25). With nn.Flatten(0, 2), it instead produces (160, 5).
Follow-up: Why is the second result 160? The dimensions 0, 1, and 2 are multiplied: 32 × 1 × 5 = 160.
torch.flattentorch.nn.Unflattentorch.nn.Sequential