Four functions, four array moves
Model coding rounds ask you to write attention, a small GPT or backprop in NumPy or PyTorch. Most lines of those programs make one of a few array moves: reduce along an axis and use the result on the same table, pick one entry per row, add an axis, or multiply stacks of matrices. A wrong move often runs with no error. This lesson's practice problem puts the moves in four small functions:
Write four NumPy functions with no Python loops over rows, positions or batches.
...means any number of leading axes, like a batch and heads.
normalize_rows(x):xis(..., n)with positive entries. Return the same shape, with each row divided by its own sum.standardize(x, eps=1e-5): return the same shape, with each row shifted to mean 0 and divided bysqrt(var + eps), wherevaris the row's variance.pick(probs, labels):probsis(..., k), andlabelsholds one class number per row, shape(...). Return each row's probability at its label.cosine_scores(a, b):ais(..., n, d)andbis(..., m, d). Return(..., n, m): the cosine similarity of every row ofawith every row ofb.
Call Returns normalize_rows([[1, 3], [2, 2]])[[0.25, 0.75], [0.5, 0.5]]standardize([[1, 2, 3]])[[-1.22, 0, 1.22]], roundedpick([[0.7, 0.2, 0.1], [0.1, 0.8, 0.1]], [0, 1])[0.7, 0.8]cosine_scores([[1, 0]], [[2, 0], [0, 3]])[[1, 0]]
The tests use square inputs on purpose. On a square table, a missing keepdims runs with no error and gives wrong numbers. By the end of Part 2 you'll see why, and you'll spot it on sight.
This lesson teaches the moves one at a time on one small table, students' scores on three tests: shapes and axes, keepdims, broadcasting, picking entries, and @ on stacks. Thirteen steps end with a small task in the editor. The whole problem comes back at the end, as the lesson's practice, from a blank file.