Creating and Reshaping NumPy Arrays
Neural networks are strict about the shape of their inputs. A batch of 32 images, each 28×28 pixels with 3 colour channels, must arrive as a tensor of shape (32, 28, 28, 3) — not as a flat list. The two operations you will use constantly are reshape and transpose.
Reshape: Changing the View Without Changing the Data
Reshape rearranges the same elements into a new shape. The only rule: the total number of elements must stay identical. A shape of (12,) can become (3, 4), (2, 6), or (2, 2, 3) — all have 12 elements.
Using -1 in a dimension tells NumPy to compute it automatically.
Reshape in Practice
Flatten and Ravel: Collapsing Back to 1D
Before passing data into a dense (fully-connected) neural network layer, you often need to flatten a multi-dimensional tensor into a 1D vector. flatten() always returns a copy; ravel() returns a view when possible (faster, less memory).
Flatten vs. Ravel
Transpose: Swapping Axes
Transposing flips the axes of an array. For a 2D matrix this swaps rows and columns ($A \to A^T$). For higher-dimensional tensors, .transpose(axes) lets you specify exactly which axes to swap.
This is used heavily when converting between 'channels first' and 'channels last' image formats between different frameworks.