v9.1.1
Menu

Flatten Feature Map

easyPROCNNsDeep LearningCV: Deep Learning

Implement a function to transform a 3D feature map into a 1D vector, a crucial step in Convolutional Neural Networks (CNNs). This process enables the connection of convolutional layers to fully connected layers.

In CNNs, a feature map is a 3D array of size C×H×WC \times H \times W, where CC is the number of channels, HH is the height, and WW is the width. To feed this data into a fully connected layer, it must be flattened into a 1D vector.

The values must appear in channel, then row, then column order: all of channel 1 comes before channel 2, within a channel row 1 comes before row 2, and within a row the values keep their left-to-right order. Return the result as a flat Python list of length C⋅H⋅WC \cdot H \cdot W.

Flattened Vector=[x1,1,1,x1,1,2,...,xC,H,W]\text{Flattened Vector} = [x_{1,1,1}, x_{1,1,2},..., x_{C,H,W}]

This technique is widely used in image classification tasks.

Example

Input
flatten([[[1,2],[3,4]], [[5,6],[7,8]]])
Output
[1,2,3,4,5,6,7,8]
Reasoning
  • Input: a nested list with C=2C = 2 channels, each an H×W=2×2H \times W = 2 \times 2 grid. Channel 1 holds [1234]\begin{bmatrix}1&2\\3&4\end{bmatrix} and channel 2 holds [5678]\begin{bmatrix}5&6\\7&8\end{bmatrix}.
  • Output size: the vector has C⋅H⋅W=2⋅2⋅2=8C \cdot H \cdot W = 2 \cdot 2 \cdot 2 = 8 entries, one per value, none added or dropped.
  • Where each value lands: counting from 0, entry xc,h,wx_{c,h,w} goes to position p=c⋅HW+h⋅W+w=4c+2h+wp = c \cdot HW + h \cdot W + w = 4c + 2h + w. So 66 (channel c=1c=1, row h=0h=0, column w=1w=1) lands at p=4+0+1=5p = 4 + 0 + 1 = 5, and 77 (c=1,h=1,w=0c=1, h=1, w=0) lands at p=6p = 6.
  • Result: positions 0 to 3 are channel 1 read row by row (1, 2, 3, 4), positions 4 to 7 are channel 2 (5, 6, 7, 8), giving [1,2,3,4,5,6,7,8].
  • Notice that the column index changes fastest and the channel index slowest. Reading columns first would give 1,3,2,41, 3, 2, 4 for channel 1 instead.

Constraints

  • Return flattened list in C, H, W order

Learn this in

More from CV: Deep Learning

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.