Course contentsShow
← Machine Learning and Deep Learning
Lesson 154 of 3,5382. Machine Learning Mindset and Core ConceptsFree lesson

Reshaping and Transposing Arrays

Using reshape, flatten, ravel, and transpose to convert between row/column vectors and match expected input dimensions.

Reshaping and Transposing Arrays

What you'll learn: How to change array shapes and orientations to match what ML algorithms expect as input.

Machine learning models are picky about input shapes. A model might expect a 2D array with samples in rows, but your data arrives as a flat 1D array. Or you need to flip rows and columns. This is where reshaping and transposing save the day.

The Core Idea

Think of your data like LEGO bricks. Reshaping rearranges the same bricks into a different configuration—same pieces, new shape. Transposing flips the structure along a diagonal, swapping rows and columns.

Key Operations

reshape(new_shape) – Changes array dimensions while preserving total elements. If you have 12 numbers, you can reshape to (3, 4), (4, 3), (2, 6), etc.

flatten() and ravel() – Convert any array into a 1D array (like unrolling a matrix into a single line). flatten() creates a copy; ravel() tries to return a view (more memory-efficient).

transpose() or .T – Swaps rows and columns. A (3, 4) array becomes (4, 3). Critical when converting between row vectors (1, n) and column vectors (n, 1).

Why This Matters in ML

Many algorithms expect specific shapes:

  • Neural networks need inputs as (samples, features)
  • A single prediction might need reshaping from (n,) to (1, n) or (n, 1)
  • Image data often reshapes from (height, width, channels) to flat vectors

Key Takeaway: Reshaping and transposing don't change your data's content—they reorganize it to match the dimensional expectations of ML models. Mastering these operations prevents "shape mismatch" errors that plague beginners.