Shape and Reshape

Every array has a shape describing its size along each axis; reshape rearranges it.

Syntaxarray.reshape(rows, cols)

The shape of an array is a tuple giving its length along each axis. A 3×4 array has shape (3, 4): 3 rows, 4 columns.

A 2D NumPy array with shape (3, 4), axis 0 running down the rows and axis 1 running across the columnsndarray shape = (3, 4)axis 1 (columns)axis 0 (rows)0123456789101112 elements • ndim = 2 • size = 12
A NumPy array of shape (3, 4): axis 0 indexes the rows, axis 1 indexes the columns.

Reshaping

reshape returns a new view with a different shape but the same data. The total number of elements must stay the same.

Use -1 to let NumPy compute one dimension for you.

Example

Example · python
import numpy as np

a = np.arange(12)
print(a.shape)          # (12,)

b = a.reshape(3, 4)
print(b.shape)          # (3, 4)
print(b.ndim)           # 2

c = a.reshape(2, -1)    # -1 -> NumPy infers 6
print(c.shape)          # (2, 6)

When to use it

  • An ML engineer reshapes a flat 784-element pixel array into a 28x28 matrix to visualise a handwritten digit from the MNIST dataset.
  • A batch-training loop uses reshape to turn a 1D vector of labels into a (batch_size, 1) column vector required by a loss function.
  • A data pipeline flattens a 3D image tensor of shape (H, W, C) to a 1D feature vector before feeding it to a scikit-learn classifier.

More examples

Inspect and change shape

Creates a flat 12-element array, checks its shape attribute, then reshapes it into a 3x4 matrix.

Example · python
import numpy as np

arr = np.arange(12)
print(arr.shape)       # (12,)

matrix = arr.reshape(3, 4)
print(matrix.shape)    # (3, 4)
print(matrix)

Flatten and use -1 wildcard

Uses -1 to let numpy infer the correct dimension size, first flattening an image and then adding a batch dimension.

Example · python
import numpy as np

img = np.ones((28, 28))        # grayscale image
flat = img.reshape(-1)         # auto-infer length = 784
print(flat.shape)              # (784,)

batch = flat.reshape(1, -1)    # add batch dimension
print(batch.shape)             # (1, 784)

Transpose a feature matrix

Transposes a feature matrix with .T, swapping rows and columns, which is required for certain linear algebra operations like covariance computation.

Example · python
import numpy as np

X = np.random.randn(100, 5)  # 100 samples, 5 features
print(X.shape)               # (100, 5)

XT = X.T
print(XT.shape)              # (5, 100) - transposed

Discussion

  • Be the first to comment on this lesson.