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

<pre><code class="language-python">import numpy as np arr = np.arange(12) # [0, 1, 2, ..., 11] matrix = arr.reshape(3, 4) # 3 rows, 4 columns cube = arr.reshape(2, 2, 3) # 3D tensor auto = arr.reshape(3, -1) # NumPy figures out -1 → 4 print(matrix.shape) # (3, 4) print(cube.shape) # (2, 2, 3) </pre>

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

<pre><code class="language-python">M = np.array([[1, 2, 3], [4, 5, 6]]) flat = M.flatten() # [1, 2, 3, 4, 5, 6] (copy) flat2 = M.ravel() # [1, 2, 3, 4, 5, 6] (view if possible) # Common in CNNs before the dense layer: batch = np.random.rand(32, 28, 28) # 32 grayscale images flattened = batch.reshape(32, -1) # (32, 784) </pre>

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.

Transpose Examples

<pre><code class="language-python">A = np.array([[1, 2, 3], [4, 5, 6]]) # shape (2, 3) print(A.T.shape) # (3, 2) — rows and cols swapped # 3D tensor: (batch, height, width) → (batch, width, height) imgs = np.random.rand(32, 64, 64) swapped = imgs.transpose(0, 2, 1) # shape (32, 64, 64) </pre>