v9.1.1
Menu

Use nn.Flatten Layer

easyFREEModelingPyTorch ModelingPytorch

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

Input
batch_size=2, channels=3, height=4, width=4
Output
{'input_shape': [2, 3, 4, 4], 'output_shape': [2, 48], 'flattened_features': 48}
Reasoning
  • Inputs: batch_size=2, channels=3, height=4, width=4 describe a batch of 2 images, each with 3 channels on a 4×44 \times 4 grid. The random tensor therefore has shape [2, 3, 4, 4], which is input_shape.
  • The math: flattening unrolls everything except the batch axis into one long vector. Each image holds C×H×W=3×4×4=48C \times H \times W = 3 \times 4 \times 4 = 48 numbers, so each one becomes a vector of length 48.
  • Output shape: the batch axis is untouched, giving 2×482 \times 48, i.e. output_shape is [2, 48]. The total element count is unchanged: 2⋅3⋅4⋅4=96=2⋅482 \cdot 3 \cdot 4 \cdot 4 = 96 = 2 \cdot 48.
  • flattened_features is 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 1×28×281 \times 28 \times 28 MNIST image would flatten to 784784 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

Learn this in

More from Pytorch

solution.py

Test results

Sign in to run your code against the test cases.