Use nn.Flatten Layer
Problem Statement
Use nn.Flatten to convert multi-dimensional tensors to 1D (per batch).
Background
When connecting convolutional layers to fully connected layers, you need to flatten the spatial dimensions while keeping the batch dimension intact. nn.Flatten does this automatically.
Your Task
Write a function apply_flatten(batch_size, channels, height, width) that creates a random tensor with the given shape, flattens it, and returns information about the shapes before and after.
Output Format
Return a dictionary with keys: "input_shape" (list), "output_shape" (list), "flattened_features" (int).
Example
batch_size=2, channels=3, height=4, width=4
{'input_shape': [2, 3, 4, 4], 'output_shape': [2, 48], 'flattened_features': 48}- Inputs:
batch_size=2,channels=3,height=4,width=4describe a batch of 2 images, each with 3 channels on a grid. The random tensor therefore has shape[2, 3, 4, 4], which isinput_shape. - The math: flattening unrolls everything except the batch axis into one long vector. Each image holds numbers, so each one becomes a vector of length 48.
- Output shape: the batch axis is untouched, giving , i.e.
output_shapeis[2, 48]. The total element count is unchanged: . flattened_featuresis the per-sample length, 48. This is exactly the input size a fully connected layer placed after this point would need.- Notice: the random values never matter here, only the shapes. A MNIST image would flatten to features per sample, and a batch of 4 would stay 4 rows.
Constraints
- Use nn.Flatten()
- Batch dimension should be preserved
- Use torch.randn for random tensor