NumPy and Array Thinking
N-dimensional arrays, vectorization and broadcasting: the mental model underneath pandas, scikit-learn and every tensor library.
Beginner · about 10 hours · difficulty 2/5
Learn first: Python for Machine Learning
NumPy's ndarray is a block of typed numbers with a shape. Nearly all ML data (tables, images, batches of embeddings) ends up as arrays, and PyTorch tensors behave almost identically, so time spent here transfers directly to deep learning.
Key ideas
- Shape, dtype and axes:
X.shape == (n_samples, n_features)is the universal convention. Know whataxis=0versusaxis=1means insumormean. - Vectorization: replace Python loops with whole-array operations; it is often 10-100x faster.
- Broadcasting: how
X - X.mean(axis=0)subtracts a row vector from every row. Learn the rules (align trailing dims, size 1 stretches). - Indexing: slicing, boolean masks (
X[y == 1]), fancy indexing, and views versus copies. - Linear algebra:
@for matrix multiply,np.linalgfor solves, norms and eigen decompositions. - Random numbers: use
rng = np.random.default_rng(42)for reproducible experiments.
Pitfalls
Silent broadcasting of shapes like (n,) against (n, 1) producing an (n, n) matrix is a classic bug. Print shapes constantly. Also beware integer dtypes truncating division results.
Good enough to move on when you can implement standardization, a pairwise distance matrix and a one-line softmax without loops.
Key concepts
- ndarray, shape and dtype
- Vectorized operations
- Broadcasting rules
- Slicing, masks and fancy indexing
- Views versus copies
- np.linalg basics
- Random Generator API
- einsum: Handy later for attention math
Mini project
Implement k-nearest-neighbour classification on the scikit-learn digits dataset using only NumPy: vectorized distance matrix, argsort, majority vote, and accuracy.
Check yourself
What shape does `a - b` produce if `a` has shape (5,) and `b` has shape (5, 1), and why?
Free resources
- NumPy user guide (numpy.org)
- NumPy: the absolute basics for beginners (numpy.org)