NumPy foundations practice problems
23 problems · 0 solved
NumPy is the base layer for almost all ML code in Python, and the same ideas carry over to PyTorch and JAX. The key skill is thinking in whole arrays instead of loops, using broadcasting and indexing to do in one line what would take many. These problems build that habit with tasks taken from real model code. You will one-hot encode labels with fancy indexing, turn rows of counts into probabilities, pick the log-probability of the correct token at every position, compute all pairwise distances without a loop, rank scores so ties share a place, pad variable-length token lists into a batch with a mask, average only the real tokens in a padded batch, compute a masked logsumexp that never overflows, cut a sequence into overlapping windows, return the top k values per row with stable ties, and apply a stable softmax inside groups of a flat array. Start with the Easy problems on one-hot encoding and pairwise distances. Then do padding, masking and logsumexp, and finish with top k and grouped softmax. Clean vectorised code is what interviewers look for, and it makes your training code faster and easier to debug.
Easy 10
- Compute every pairwise distance without a Python loop
- One-hot encode class labels with fancy indexing
- Rank leaderboard scores so ties share a place
- Undo a length sort with the inverse permutation from argsort
- Remap sparse token ids to a compact vocabulary with np.unique
- Average values per group id with weighted bincount
- Divide arrays safely with a fill value where the denominator is zero
- Add per-query and per-document biases to a score matrix with broadcasting
- Turn each row of counts into a probability distribution
- Pick the log-probability of the correct token at every position
Medium 9
- Average only the real tokens in a padded batch
- Cut a token sequence into overlapping fixed-size windows
- Answer many range-sum queries in constant time with prefix sums
- Assign sequences to length buckets with searchsorted and count padding
- Compute all pairwise Jaccard similarities from a binary matrix
- Build a causal mask that also blocks attention across packed documents
- Sort a leaderboard by score, then latency, then name with np.lexsort
- Pad variable-length token lists into a batch with a mask
- Compute a masked logsumexp that never overflows