PyTorch Introduction - Neural Networks

In this notebook we build on top of the previous notebook, and show how to build, train and evaluate neural networks in PyTorch.

Import and Helper Functions

Here we import torch, define helper function for visualization and define dataset for later use.

torch.nn.Module

Module is PyTorch's way of performing operations on tensors. Modules are implemented as subclasses of the torch.nn.Module class. All modules are callable and can be composed together to create complex functions.

torch.nn docs

Note: most of the functionality implemented for modules can be accessed in a functional form via torch.nn.functional, but these require you to create and manage the weight tensors yourself.

torch.nn.functional docs.

Linear Module

The bread and butter of modules is the Linear module which does a linear transformation with a bias. It takes the input and output dimensions as parameters, and creates the weights in the object.

Unlike how we initialized our $w$ manually, the Linear module automatically initializes the weights randomly. For minimizing non convex loss functions (e.g. training neural networks), initialization is important and can affect results. If training isn't working as well as expected, one thing to try is manually initializing the weights to something different from the default. PyTorch implements some common initializations in torch.nn.init.

torch.nn.init docs

Activation functions

PyTorch implements a number of activation functions including but not limited to ReLU, Tanh, and Sigmoid. Since they are modules, they need to be instantiated.

Sequential

Many times, we want to compose Modules together. torch.nn.Sequential provides a good interface for composing simple modules.

Note: we can access all of the parameters (of any nn.Module) with the parameters() method.

Loss functions

PyTorch implements many common loss functions including MSELoss and CrossEntropyLoss.

torch.optim

PyTorch implements a number of gradient-based optimization methods in torch.optim, including Gradient Descent. At the minimum, it takes in the model parameters and a learning rate.

Optimizers do not compute the gradients for you, so you must call backward() yourself. You also must call the optim.zero_grad() function before calling backward() since by default PyTorch does and inplace add to the .grad member variable rather than overwriting it.

This does both the detach_() and zero_() calls on all tensor's grad variables.

torch.optim docs

As we can see, the parameter was updated in the correct direction

Linear regression using GD with automatically computed derivatives and PyTorch's Modules

Now let's combine what we've learned to solve linear regression in a "PyTorchic" way.

Linear regression using SGD

In the previous examples, we computed the average gradient over the entire dataset (Gradient Descent). We can implement Stochastic Gradient Descent with a simple modification.

Neural Network Basics in PyTorch

Let's consider the dataset from hw3. We will try and fit a simple neural network to the data.

Here we define a simple two hidden layer neural network with Tanh activations. There are a few hyper parameters to play with to get a feel for how they change the results.

Things that might help on the homework

Brief Sidenote: Momentum

There are other optimization algorithms besides stochastic gradient descent. One is a modification of SGD called momentum. We won't get into it here, but if you would like to read more here is a good place to start.

We only change the step size and add the momentum keyword argument to the optimizer. Notice how it reduces the training loss in fewer iterations.

Briefer Sidenote: Learning rate schedulers

Often we do not want to use a fixed learning rate throughout all training. PyTorch offers learning rate schedulers to change the learning rate over time. Common strategies include multiplying the lr by a constant every epoch (e.g. 0.9) and halving the learning rate when the training loss flattens out.

See the learning rate scheduler docs for usage and examples

CrossEntropyLoss

So far, we have been considering regression tasks and have used the MSELoss module. For the homework, we will be performing a classification task and will use the cross entropy loss.

PyTorch implements a version of the cross entropy loss in one module called CrossEntropyLoss. Its usage is slightly different than MSE, so we will break it down here.

Try out the loss function on three toy predictions. The true class labels are $y=[1,1,0]$. The first two examples correspond to predictions that are "correct" in that they have higher raw scores for the correct class. The second example is "more confident" in the prediction, leading to a smaller loss. The last two examples are incorrect predictions with lower and higher confidence respectively.

Convolutions

When working with images, we often want to use convolutions to extract features using convolutions. PyTorch implements this for us in the torch.nn.Conv2d module. It expects the input to have a specific dimension $(N, C_{in}, H_{in}, W_{in})$ where $N$ is batch size, $C_{in}$ is the number of channels the image has, and $H_{in}, W_{in}$ are the image height and width respectively.

We can modify the convolution to have different properties with the parameters:

They can change the output dimension so be careful.

See the torch.nn.Conv2d docs for more information.

To illustrate what the Conv2d module is doing, let's set the conv weights manually to a Gaussian blur kernel.

We can see that it applies the kernel to the image.

As we can see, the image is blurred as expected.

In practice, we learn many kernels at a time. In this example, we take in an RGB image (3 channels) and output a 16 channel image. After an activation function, that could be used as input to another Conv2d module.

Recurrent Neural Networks

When working with text, we often want to use text embeedings and recurrent neural networks. This is because we have to:

  1. Represent words (or characters) as a vector.
  2. Typically meaning of a word depends on a context ("March is a cold month." vs "Their march was very loud.")

PyTorch implements these concept using torch.nn.Embedding and torch.nn.RNN.

Embedding converts a list of $n$ words into an $\mathbb{R}^{n \times d}$ matrix, where each word is respresented by $\mathbb{R}^d$ vector. When creating it you need to provide number of words in your dictionary, and the embedding size: $d$.

RNN allows us to use context by having the output $y$ be the function of input $x$, which we provide and the hidden state, which depends on previous inputs in a sequence. The layer takes input of (sequence length, batch size, $d_{in}$), and an optional argument for hidden state. It's output is a tuple containing actual output (sequence length, batch size, $d_{out}$), and hidden state.

For a longer explanation take a look a this post. While it's on topic of LSTMs the beginning does a good explanation of how RNNs work. If you really want to take a deep dive this post goes in-depth on various applications of RNNs and LSTMs.

Lastly if that's something that you are interested in consider CSE 447 (NLP).

Beyond - More advanced example. Predicting next word.