AI Engineering: NumPy & PyTorch
Learn the two tools machine learning is written in: NumPy for thinking in whole arrays, and PyTorch for gradients, models and training loops. Every snippet really runs, and the bugs you hunt are the ones that eat real afternoons.
- Intermediate
- 4 units, 12 lessons, 154 exercises
- Python
- Builds on Math for ML
Unit 01 · 3 lessons
NumPy
Think in whole arrays instead of loops
- 01Arrays
Shapes, slices, masks and why loops disappear
- 02Broadcasting
How arrays of different shapes combine, and the bug that hides there
- BOSSWhich axis
Reduce, reshape and normalise a batch without mixing up rows and columns
Read the unit guide
A NumPy array is a grid of numbers that all share one type, packed side by side in memory. Its shape says how many numbers lie along each axis and its dtype says what kind they are. Arithmetic on an array applies to every element at once, in one compiled loop, which is why a * 2 beats a Python for loop by a wide margin even though both are O(n). Snippets in this roadmap assume import numpy as np.
Indexing works like nested lists with commas: a[1, 2] is row 1, column 2, and a[:, 0] is the first column. A comparison such as a > 5 gives an array of True and False, called a mask. a[mask] keeps the matching elements and mask.sum() counts them.
A plain slice is a view: it shares memory with the original, so writing through it changes both. Indexing with a mask or a list copies. When in doubt, .copy().
Broadcasting lets arrays of different shapes meet. Line the shapes up from the right: two sizes fit when they are equal or one of them is 1, and a missing axis counts as 1. So a (3, 2) array plus a (2,) array adds the small one to every row. The trap is (n,) against (n, 1): no error, an (n, n) result, and a wrong answer.
Reductions such as sum, mean and argmax take an axis: the axis you name is the one that disappears. On a (samples, features) batch, axis=0 gives one number per feature and axis=1 one per sample. keepdims=True leaves the axis in place with size 1 so the result still broadcasts.
reshape re-cuts the same numbers in the same reading order (-1 means "work this one out"), while .T really swaps rows and columns. They can give the same shape and different data, so never use one for the other.
Unit 02 · 3 lessons
Tensors and autograd
Use arrays that remember how they were computed
- 01Tensors
NumPy habits that carry over, and the three that do not
- 02Autograd
Let PyTorch do the calculus, and learn its three habits
- BOSSGradient descent by hand
Fit a line with raw tensors and meet every classic loop bug
Read the unit guide
A PyTorch tensor is a NumPy array with two extras: it can live on a GPU, and it can record the operations done to it. Indexing, slicing, broadcasting and reductions work as in NumPy, with dim in place of axis. Floats default to float32, not NumPy's float64, and PyTorch refuses to mix dtypes or devices silently. Snippets assume import torch.
view and reshape re-cut the same memory, and torch.from_numpy shares memory with the array it came from. Methods ending in an underscore, such as mul_ or zero_, change the tensor in place. Use .item() to pull a plain Python number out of a one-element tensor.
Autograd is the reason PyTorch exists. A tensor made with requires_grad=True has every operation on it recorded in a graph. Calling backward() on a result walks that graph in reverse with the chain rule and leaves the gradient in each input's .grad.
Gradients accumulate: each backward() adds to .grad, so it must be zeroed between steps. Inside with torch.no_grad(): nothing is recorded, which is what a parameter update needs. detach() gives one tensor's values with its history cut off.
Gradient descent by hand is five moves on repeat: predict, compute the loss, call backward(), step each parameter against its gradient under no_grad(), zero the gradients. Nearly every training bug is one of those moves missing, doubled or out of order.
The classic mistakes: updating outside no_grad() (an error), writing w = w - lr * w.grad (a new tensor that is no longer the parameter), forgetting to zero (the loss bounces), zeroing before the update (nothing moves), and a learning rate so large the loss explodes.
Unit 03 · 3 lessons
Training a model
Write the training loop every PyTorch project shares
- 01Modules
Layers that own their weights, and models built from layers
- 02The training loop
Losses, optimizers and the five lines in the right order
- BOSSTrain a classifier
Batches, a validation split and a model that learns from 200 points
Read the unit guide
torch.nn packages what you built by hand. nn.Linear(n_in, n_out) holds a weight of shape (n_out, n_in) and a bias of shape (n_out,), both already tracking gradients, and maps a batch of shape (N, n_in) to (N, n_out). Your own model is a class that extends nn.Module: create the layers in __init__ (after super().__init__()) and say how data flows in forward. Snippets assume import torch.nn as nn and from torch import optim.
Layers only add power with an activation between them: stacked Linear layers with nothing in between collapse into one. nn.ReLU zeroes negatives and is the default choice. nn.Sequential runs layers in order, and model.parameters() hands every learnable tensor to the optimizer.
The training loop is five lines: opt.zero_grad(), pred = model(x), loss = loss_fn(pred, y), loss.backward(), opt.step(). The optimizer does the update you once wrote under no_grad(), for every parameter it was given. One pass over all the data is an epoch.
Pick the loss for the job. nn.MSELoss for predicting numbers. nn.CrossEntropyLoss for picking a class: it takes raw scores (logits) of shape (N, C) and integer class indexes of shape (N,), and applies softmax itself. A fresh classifier's loss should sit near ln(C).
A Dataset answers two questions, how many samples and what is sample i; a DataLoader shuffles it and stacks samples into batches. Hold back a validation split the model never trains on, and compute anything you learn from the data, such as normalisation statistics, on the training part only.
model.train() and model.eval() switch layers like dropout between their training and prediction behaviour. Evaluate under eval() and torch.no_grad(), and log loss.item(), never the loss tensor itself.
Unit 04 · 3 lessons
In practice
Debug, measure and reuse models like someone who does it daily
- 01Debugging models
Find the bug when nothing crashes and nothing learns
- 02Evaluation
Numbers that tell you whether the model is any good
- BOSSStand on a trained model
Load weights, freeze the body, train a new head
Read the unit guide
Most training bugs raise no error. Work down a ladder: print the shapes of the inputs, outputs and targets; check dtypes and devices; then see whether the model can overfit one tiny batch. A working model, loss and loop will memorise 8 samples almost perfectly. If they cannot, the bug is in the pipeline, and you found it in seconds.
Know the symptoms. A loss frozen at ln(classes) means the parameters are not updating: a stale optimizer, a missing step(), frozen layers. A loss that bounces or explodes points at the learning rate or a missing zero_grad(). NaN usually starts as log(0) or an exploding step, and then poisons everything after it. Double versus Float is NumPy's float64 meeting float32 weights.
Accuracy lies when classes are lopsided: predicting the common class every time scores well and finds nothing. Precision asks how many of the flagged cases were right, and recall how many of the real cases were caught. Which one matters depends on which mistake costs more.
Compare training and validation loss. Both high is underfitting. Training low and validation rising is overfitting: keep the checkpoint where validation was best, and make memorising harder with dropout, weight decay or more data. Seed your runs so results repeat.
A model's learned state is its state_dict, a dict from parameter name to tensor. Save that, and load it into the same architecture. To reuse a trained model on a new task, load it, freeze its parameters with requires_grad = False, replace the last layer (new layers start trainable), and train only the new part, or give the old part a much smaller learning rate.
Predict under model.eval() and torch.no_grad(): dropout off, nothing recorded.
Learn AI Engineering: NumPy & PyTorch on your phone.
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.