Skip to content

0.2 NumPy and PyTorch tensors

ready≈ 5 hoursNeeds: 0.1Unlocks: 1.1, 1.4, 4.4
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (Tensor shape tracer)
  4. 4 Do
  5. 5 Check

Almost every bug in ML code is a shape bug, so this module is about shapes.

An array has a shape (a tuple, one entry per axis) and a dtype. X.shape == (n, d) means n rows of d features. Reductions take an axis: X.mean(axis=0) averages down the rows and leaves shape (d,). Add keepdims=True to keep that axis as length 1 so the result still broadcasts against X (NumPy basics).

Broadcasting lets arrays of different shapes combine without copying. NumPy lines the shapes up from the right. Each pair of sizes must be equal, or one of them must be 1 (which stretches) (broadcasting rules). So (n, d) - (d,) subtracts a vector from every row, and (n, 1, d) - (1, m, d) gives all n × m pairwise differences, shape (n, m, d). That one trick replaces most double loops.

Indexing with integer arrays picks elements, not slices: S[np.arange(n), idx] takes one entry per row, S[i, idx[i]] for every i. This is exactly how a classification loss picks out each example’s correct-class score (indexing). Elementwise product a⊙b\mathbf{a} \odot \mathbf{b}elementwise productMultiply matching entries: (a ⊙ b)_i = a_i b_i. NumPy writes a * b.Introduced in 0.2 NumPy and PyTorch tensors. is a * b, while matrix product is a @ b.

PyTorch tensors follow the same rules and nearly the same names (torch.zeros, .shape, .sum(dim=0)). Two differences matter from Part 3 on: tensors live on a device (.to("cuda")), and they can record operations for automatic differentiation. torch.from_numpy shares memory with the NumPy array, so changing one changes the other (PyTorch tensors). The exercises here are NumPy only, so they run in your browser. Everything transfers.

Habit to build now: before running a line, say its output shape out loud. The tracer below checks you.

Tensor shape tracer

Shape reasoning

Static view on small screens. Open this page on a laptop to interact.

import numpy as np

X = np.random.default_rng(0).normal(size=(4, 3))   # 4 points in 3-D
Y = np.ones((5, 3))                                   # 5 more points
mu = X.mean(axis=0)
Xc = X - mu                          # (4, 3) - (3,) broadcasts
diff = X[:, None, :] - Y[None, :, :]
D = (diff ** 2).sum(axis=-1)         # all pairwise squared distances
nearest = D.argmin(axis=1)
scores = np.arange(12.0).reshape(4, 3)
picked = scores[np.arange(4), nearest % 3]

Tab indents · Esc then Tab leaves the editor · Shift+Enter runs

Python runs in the page and annotates every line with the dtype and shape of each variable it creates or changes. Predict each shape before you press the button. Keyboard: edit the code; Shift+Enter traces.

A scratch cell for your own experiments (cells on a page share variables):

a = np.arange(3)          # shape (3,)
b = np.arange(4)[:, None] # shape (4, 1)
(a + b).shape

Tab indents · Esc then Tab leaves the editor · Shift+Enter runs

Seven drills, no Python loops allowed. Each one is a pattern you will use again.

Broadcasting and indexing drills stubs/m0_2_tensors.py

Loading starter file…

Prefer your own editor? Edit exercises/stubs/m0_2_tensors.py and run mlc check 0.2. The tests are identical; import the results on the progress page.

Hints · pairwise_sq_dists 0/3 revealed
Hints · causal_mask 0/3 revealed

Locally: mlc check 0.2.

1. What is the shape of A + B for A.shape == (8, 1, 6) and B.shape == (7, 1)?
2. X has shape (100, 5). What is X.sum(axis=1, keepdims=True).shape?
3. S has shape (4, 3) and idx = [2, 0, 1, 1]. What does S[np.arange(4), idx] return?
4. Which subtraction centres the columns of X (shape (n, d))?
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
Learner log: time spent and points of confusion

Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.