NumPy & Arrays
Vectorized math, broadcasting, shapes — a 28×28 image is just a NumPy array of 784 numbers.
Every image your phone camera takes is a 3D NumPy array: height × width × 3 (RGB). Instagram's filters? NumPy math on pixels. Face detection? NumPy arrays sliced and convolved.
Python loops over pixels would take 10 seconds per photo. NumPy vectorization does it in 0.001 seconds. That's why every AI framework is built on NumPy.
📈 Core Concepts (5–25 min)
Shape — dimensions of the array: (28, 28) = 28 rows, 28 cols.
Vectorization — operations apply to ALL elements at once (no loop needed).
Broadcasting — arrays with different shapes can combine: (3,) + (3,1) works automatically.
💻 Live Demo (25–45 min)
>import numpy as np # 1. Shapes — think of arrays as tensors pixel_row = np.array([255, 128, 0, 64, 200]) # 1D: shape (5,) image = np.zeros((28, 28)) # 2D: 28x28 grayscale rgb_img = np.zeros((28, 28, 3)) # 3D: 28x28 colour print(image.shape, image.dtype) # (28, 28) float64 # 2. Vectorization — no loop, math on all at once scores = np.array([45, 78, 92, 60, 55]) normalized = (scores - scores.min()) / (scores.max() - scores.min()) print(normalized) # all values in [0.0, 1.0] # 3. Broadcasting — align shapes automatically # Subtract mean from each row (centering data) data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) row_means = data.mean(axis=1, keepdims=True) # shape (3,1) centered = data - row_means # broadcasts: (3,3) - (3,1) # 4. Indexing and slicing big = np.arange(100).reshape(10, 10) patch = big[2:5, 3:7] # rows 2-4, cols 3-6 mask = scores > 60 # boolean mask print(scores[mask]) # [78 92]
When you load an image with PIL/OpenCV, it becomes a NumPy array. Resize = array slice + interpolation. Brightness = array multiply. Grayscale = weighted sum across axis 2.
📋 You Code It (45–55 min)
Create a (5, 4) random array of student test scores (0–100). Compute: row-wise mean (per student), column-wise mean (per subject), then normalize the whole matrix to [0, 1].
⚡ Day 2 Cheat Sheet
np.array([...])arr.shape / arr.dtypenp.zeros((m,n))np.random.rand(m,n)arr.mean(axis=0)arr.reshape(r, c)arr[mask]arr1 @ arr2