Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Deep Neural Networks (PyTorch)

We’re going to spend today walking through PyTorch, a popular open-source library for deep learning. We’re talking about PyTorch because I prefer it. Others prefer TensorFlow, but that number is dwindling. Others prefer JAX, particularly in the research community, but it’s a small fraction.

In general, PyTorch has good documentation, good built-in functionality, and a wide network of compatible libraries that make Deep Learning easier to get up and running. It also exposes a bit more of the machinery to the user which makes it more customizable, particularly for things that aren’t vanilla supervised learning.

There are some subtle under-the-hood differences between PyTorch and TensorFlow. I may get into those details next time, or maybe not.

PyTorch Tensors

The basic unit of operation in (py)torch is a tensor. A scalar is a rank-0 tensor. It has no index. A vector is a rank-1 tensor that can be indexed as V⃗:Vi\vec{V}: V_i. A matrix is a rank-2 tensor that can be indexed as M↔:Mij\overleftrightarrow{M}: M_{ij}. A rank-3 tensor is similarly indexed as TijkT_{ijk}.

image.png

Big Tensors

Tensors can get very large and have a large number of indices. For example, a batch of images might have 4 indices: [B,C,H,W][B, C, H, W]

Fun with tensors

We can do a lot of normal mathematical and array operations with tensors just as we would numpy arrays

Torch Datasets and DataLoaders

Torch builds in a lot of functionality that we need for training neural networks beyond the networks themselves (which we will get to). For example, data loading pipelines to serve tensors to the model during training

Multiprocessing while data loading

Gradient descent

Linear regression

Just as a teaser, let’s see how to do regression using gradient descent and PyTorch. Start by creating a dataset in numpy

How does this work?

PyTorch stores an attribute alongside each tensor called grad. We’ll talk about this next class in more detail. But in a nutshell, this piece is populated when we call backward() after making the forward pass.

A more PyTorch way of doing it

Polynomial regression

How would you implement a model to fit the following dataset?

Neural networks

Let’s train a neural network to fit the XOR dataset

Dataset creation

Model implementation

Training loop

Analysis

Activation functions

Deep MLP