In this section we build and train basic neural networks with PyTorch.
Supervised Learning¶
Supervised learning has three ingredients:
data: pairs , , of inputs and the outputs we want to predict, such as images of handwritten digits and the digits they show;
a model , a family of functions indexed by parameters ;
a loss that measures how far a prediction is from the truth .
Training chooses the parameters that minimize the average loss over the data,
For a linear model and the squared loss , this is a linear least squares problem. For a neural network it is a non-convex optimization problem in many variables, and it is solved with variants of stochastic gradient descent (Optimization Algorithms). Each step estimates the gradient of from a random mini-batch of the data.
A small training loss is not the goal, though. We want a model that generalizes, that is, one that predicts well on data it has not seen. So we set aside a test set that is never used for training, and judge the model by its error there.
Neural Networks¶
A (deep) neural network is the composition of functions
where each layer is a (non-linear) function with learnable parameters , and collects the parameters of all the layers. A common and simple one to describe is an (affine) linear transformation followed by a non-linearity
where is matrix-vector multiplication, and the activation function is applied to each entry. A popular choice is the ReLU (Rectified Linear Unit)
and others are and the sigmoid .
Without the activations, the composition would be a single affine map. With them, a network with one wide enough hidden layer can approximate any continuous function on a bounded set (the universal approximation theorem). Other architectures build in the structure of the data: convolutional networks for images (Convolutions and Fourier Transforms), graph neural networks for graphs, and transformers for sequences such as text.
Neural networks pay off when the inputs are high-dimensional and structured, like images, sound, text, or molecules, where hand-made features and classical approximation by polynomials or on grids do not scale. There are many industrial applications (e.g. at your favorite or least favorite companies in Silicon Valley), but also many scientific applications including
Processing data in particle detectors
Seismic imaging / medical imaging
Predicting protein structure from sequence
Weather forecasting
Accelerating simulations of physical phenomena (Scientific Machine Learning with PyTorch)
...
Regression and Classification¶
The last layer and the loss depend on the task. For regression, the network outputs numbers and the loss is usually the squared error. To classify inputs into classes, the network outputs numbers , which are turned into probabilities using softmax
The cross-entropy loss is the negative log of the probability assigned to the correct class, . We’ll use this to classify handwritten digits at the end of this section.
What a Deep Learning Library Provides¶
No matter what library or language you use, training a network needs
the gradient of with respect to all the parameters, computed by automatic differentiation;
building blocks for common architectures, losses, and optimization algorithms;
fast arithmetic, mostly multiplication of batches of matrices, on GPUs.
This section covers the first two items: automatic differentiation with torch.autograd, then torch.nn and torch.optim, and finally a classifier for handwritten digits.
Run this notebook in Google Colab with a GPU (Runtime → Change runtime type → T4 GPU). Colab has PyTorch installed, along with the torchvision package we use for the data set. To run it on your own computer, see Linear Algebra in PyTorch for how to install both.
import numpy as np
import matplotlib.pyplot as plt
import torch
import torchvision
from torchvision.datasets import MNIST
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # see Linear Algebra in PyTorch
print(torch.__version__, device)Automatic Differentiation¶
Automatic differentiation is different from numerical differentiation, which requires a choice of step size, and symbolic differentiation which creates a single expression for a derivative. Instead it performs chain rule repeatedly.
PyTorch uses dynamic computation graphs to compute the gradients of the parameters.
def model_fn(x,m,c):
return m*x + c
def loss_fn(y,yt):
return torch.linalg.vector_norm(y-yt)m = torch.tensor([5.0], requires_grad = True)
c = torch.tensor([2.0], requires_grad = True)x = torch.tensor([2.0])
yt = torch.tensor([13.0])Calling loss.backward() forces pytorch to compute the gradient of loss with respect to all the tensors used to compute loss which had the requires_grad flag set to True. The computed gradient will be stored in the .grad property of those tensors
y = model_fn(x,m,c)
loss = loss_fn(y,yt)
loss.backward()
with torch.no_grad():
m -= 0.05 * m.grad
c -= 0.05 * c.grad
m.grad.zero_()
c.grad.zero_()
print( f" m = {m}\n c = {c}\n y = {y}\n loss = {loss}")
#note that 'loss' indicates the loss for the previous m,c valuesPyTorch records every operation on a tensor with requires_grad=True, so that backward() can apply the chain rule later. Without torch.no_grad(), PyTorch would try to record the update as part of the computation, and for an in-place change to a parameter it raises an error instead.
backward() adds the new gradient to what is already in .grad instead of overwriting it. Without the reset m.grad.zero_(), the next step would move along the sum of all the gradients computed so far. Methods whose names end in an underscore, like zero_, modify a tensor in place.
Here’s an explicit loop, fitting a line to 100 noisy samples of :
x = torch.linspace(-1, 1, 100)
yt = 3 * x + 1 + 0.1 * torch.randn(100)
m = torch.tensor([5.0], requires_grad = True)
c = torch.tensor([2.0], requires_grad = True)
losses = []
for i in range(100):
y = model_fn(x,m,c)
loss = loss_fn(y,yt)
loss.backward()
with torch.no_grad():
m -= 0.01 * m.grad
c -= 0.01 * c.grad
m.grad.zero_()
c.grad.zero_()
losses+=[loss.item()]
print(f"m = {m.item():.3f}, c = {c.item():.3f}")
plt.plot(losses);Using Library functions¶
The subpackage torch.nn provides an object-oriented library of functions that can be composed together.
model = torch.nn.Sequential(
torch.nn.Linear(5, 5), # 5 x 5 matrix
torch.nn.ReLU(), # ReLU nonlinearity
torch.nn.Linear(5, 5), # 5 x 5 matrix
)list(model.parameters())loss_fn = torch.nn.MSELoss(reduction='sum')In this case, we’ll just fit the model to random data.
x = torch.randn(100,5)
yt = torch.randn(100,5)
losses = []Optimizers in torch.optim implement a variety of optimization strategies. Almost all are based on gradient descent, since forming Hessians is prohibitive. In the loop below, optimizer.step() updates all the parameters without recording the update, like the lines inside torch.no_grad() above, and optimizer.zero_grad() resets their gradients.
optimizer = torch.optim.Adam(model.parameters(), lr=0.03)for i in range(100):
y = model(x)
loss = loss_fn(y,yt)
loss.backward()
optimizer.step()
optimizer.zero_grad()
losses+=[loss.item()]
plt.plot(losses);MNIST Example¶
The MNIST data set consists of a collection of handwritten digits (0-9). Our goal is to train a neural net which will classify the image of each digit as the correct digit
We load it with the torchvision package, which provides a variety of computer vision functionality for PyTorch, including common data sets.
import torchvisionfrom torchvision.datasets import MNISTdata = MNIST(".", download=True) # 60,000 training images
test_data = MNIST(".", train=False, download=True) # 10,000 test imageslen(data)i = torch.randint(len(data), ()).item() # a random training image
img, y = data[i]
print(y)
imgdata.data[2].shape
plt.imshow(data.data[2])print(data.targets[2])
MNIST Training¶
Each training step uses a random mini-batch of 1000 training images. We flatten each image into a vector of length 784 and scale the pixel values to . The network outputs 10 logits, one per digit, and torch.nn.CrossEntropyLoss applies the softmax and the cross-entropy loss described at the beginning of this section.
model = torch.nn.Sequential(
torch.nn.Linear(784, 100),
torch.nn.ReLU(),
torch.nn.Linear(100, 100),
torch.nn.ReLU(),
torch.nn.Linear(100, 10),
).to(device) # move the parameters to the GPUloss_fn = torch.nn.CrossEntropyLoss()X_train = data.data.reshape(len(data), -1).to(device).float() / 255 # all 60,000 images, on the GPU
Y_train = data.targets.to(device)
sample = torch.randint(len(data), (1000,), device=device)
x = X_train[sample]
yt = Y_train[sample]x.shape,yt.shapeoptimizer = torch.optim.Adam(model.parameters(), lr=0.03)
losses = []for i in range(100):
sample = torch.randint(len(data), (1000,), device=device)
x = X_train[sample]
yt = Y_train[sample]
y = model(x)
loss = loss_fn(y,yt)
loss.backward()
optimizer.step()
optimizer.zero_grad()
losses+=[loss.item()]
plt.plot(losses)We measure the accuracy on the 10,000 test images, which were not used for training.
x_test = test_data.data.reshape(len(test_data), -1).to(device).float() / 255
y_test = test_data.targets.to(device)with torch.no_grad():
y_pred = model(x_test)accuracy = (y_pred.argmax(dim=1) == y_test).float().mean().item()
print(f"Accuracy = {accuracy:.3f}")Credits¶
This notebook was adapted from a notebook from CME 193 at Stanford