Reshape and Transpose - NumPy Fundamentals
Implement Reshape and Transpose in Python with NumPy. medium exercise with examples, hints, and instant feedback. No setup or signup required.
Reshape and Transpose
What you'll build
A function reshape_transpose(arr) that reshapes a 24-element vector into 2D and 3D arrays, transposes them, and flattens back.
Background
Shape changes glue ML pipelines together: flattening images before a linear layer, splitting d_model into attention heads, moving channels between (N, H, W, C) and (N, C, H, W). Mixing up reshape (same order, new grouping) and transpose (same data, axes reordered) is one of the most common silent bugs.
Key ideas
- NumPy stores arrays in row-major (C) order: the last axis changes fastest.
reshapekeeps that order and regroups it. In a(4, 6)array, entry[i, j]is element6*i + jof the vector; in a(2, 3, 4)array, entry[i, j, k]is element12*i + 4*j + k. One dimension may be-1("infer it").transposereorders axes:out = a.transpose(2, 1, 0)meansout[k, j, i] = a[i, j, k]. For 2D,a.T[j, i] = a[i, j]. No data moves; only the strides change.flatten()reads an array back out in row-major order (always a copy);ravel()does the same but returns a view when it can.
Inputs
arr: 1D array of exactly 24 elements (the tests mostly usenp.arange(24)).
Expected Return Format
Return a dictionary with these keys:
'arr_2d':arrreshaped to(4, 6)'arr_3d':arrreshaped to(2, 3, 4)'arr_2d_transposed': transpose ofarr_2d, shape(6, 4)'arr_3d_swapped':arr_3dwith its axes reversed,transpose(2, 1, 0), shape(4, 3, 2)'arr_flat':arr_2dflattened back to 1D in row-major order, shape(24,)(equal to the input)
Edge cases and conventions
arr_2d.reshape(6, 4)has the right shape but is not the transpose: its first row is[0, 1, 2, 3], while the transpose's first row is[0, 6, 12, 18].- Flattening the transposed array gives a different order (
[0, 6, 12, 18, 1, ...]), which is why'arr_flat'flattensarr_2d.
Constraints
Use reshape, transpose/.T and flatten/ravel; no loops.
Follow-up
- Convert a batch of images from
(N, H, W, C)to(N, C, H, W). Which axis order do you pass totranspose? - Why does
.view(...)on a transposed tensor fail in PyTorch, while.reshape(...)works?
Examples
Input: reshape_transpose(np.arange(24))["arr_2d_transposed"][:2]
Output: array([[ 0, 6, 12, 18],
[ 1, 7, 13, 19]])Row j of the transpose is column j of arr_2d.
Input: reshape_transpose(np.arange(24))["arr_3d_swapped"][:, 0, :]
Output: array([[ 0, 12],
[ 1, 13],
[ 2, 14],
[ 3, 15]])out[k, 0, i] = arr_3d[i, 0, k] = 12*i + k.
Input: reshape_transpose(np.arange(24))["arr_3d"].shape Output: (2, 3, 4)
The same 24 values, grouped as 2 blocks of 3 rows of 4.
Practice in Python
import numpy as np
def reshape_transpose(arr: np.ndarray) -> dict:
"""
Reshape, transpose and flatten a 24-element array.
Args:
arr: 1D array of 24 elements
Returns:
dict with keys:
'arr_2d': arr reshaped to (4, 6)
'arr_3d': arr reshaped to (2, 3, 4)
'arr_2d_transposed': arr_2d transposed, shape (6, 4)
'arr_3d_swapped': arr_3d with axes reversed (2, 1, 0), shape (4, 3, 2)
'arr_flat': arr_2d flattened back to shape (24,)
"""
# Your code here
pass
The interactive editor loads with Python and NumPy. Run your implementation against 9 tests, or use the progressive hints.