PyTorch tutorial: tensors, autograd and training loops

Learn PyTorch with 36 New York taxi trips: tensor shapes, manual gradients, autograd, nn.Linear, saved weights and DataLoader batches.

Player not loading? Watch on YouTube

Zachary Huang explains PyTorch training by fitting a line to 36 New York yellow taxi trips from three days in January 2024. The model predicts fares from distance using a weight and a bias.

The lesson starts with tensor creation, shapes and dimensions. Indexing and boolean masks select rides, while mean, max and top-k summarize fares. Examples explain which axis a reduction removes and how transpose, reshape and flatten rearrange the data.

Huang works through predictions, mean squared error and gradients by hand before introducing autograd. He explains how backward accumulates gradients, why the loop clears them between updates, and why manual parameter updates use torch.no_grad().

The same calculation then uses torch.optim.SGD and nn.Module. An nn.Linear shape error shows why 36 examples with one input each need a 36-by-1 tensor. Further examples cover inference without gradient recording, saving and loading model weights, and shuffled DataLoader batches of 12.

The final section compares SGD, momentum and Adam on the example, explains activations between linear layers, and introduces regression and classification losses. A separate taxi-speed example illustrates how an activation lets the model fit a curve. Optimizer convergence counts depend on the demonstrated settings.

The fare model uses distance alone. Huang explains that slow-traffic charges account for part of the difference between its fitted intercept and the meter's starting charge. The tutorial illustrates training mechanics without establishing predictive accuracy on held-out trips.