Files
pytorch-deep-learning/01_pytorch_workflow.ipynb
T

122 KiB

Open In Colab

01. PyTorch Workflow Fundamentals

The essence of machine learning and deep learning is to take some data from the past, build an algorithm (like a neural network) to discover patterns in it and use the discoverd patterns to predict the future.

There are many ways to do this and many new ways are being discovered all the time.

But let's start small.

How about we start with a straight line?

And we see if we can build a model with PyTorch to that straight line.

What we're going to cover

In this module we're going to cover a standard PyTorch workflow.

a pytorch workflow flowchart

For now, we'll use this workflow to predict a simple straight line but the workflow steps can be repeated and changed depending on the problem you're working on.

Specifically, we're going to cover:

Topic Contents
1. Getting data ready Data can be almost anything but for to get started we're going to create a simple straight line
2. Building a model Here we'll create a model to learn patterns in the data, we'll also choose a loss function, optimizer and build a training loop.
3. Fitting the model to data (training) We've got data and a model, now let's let the model (try to) find patterns in the (training) data.
4. Making predictions and evaluating a model (inference) Our model's found patterns in the data, let's compare its findings to the actual (testing) data.
5. Saving and loading a model You may want to use your model elsewhere, or come back to it later, here we'll cover that.
6. Putting it all together Let's take all of the above and combine it.

Where can can you get help?

All of the materials for this course live on GitHub.

And if you run into trouble, you can ask a question on the Discussions page there too.

There's also the PyTorch developer forums, a very helpful place for all things PyTorch.

Let's start by putting what we're covering into a dictionary to reference later.

In [11]:
what_were_covering = {1: "data (prepare and load)",
    2: "build model",
    3: "fitting the model to data (training)",
    4: "making predictions and evaluating a model (inference)",
    5: "saving and loading a model",
    6: "putting it all together"
}

And now let's import what we'll need for this module.

We're going to get torch, torch.nn (nn stands for neural network and this package contains the building blocks for creating neural networks in PyTorch) and matplotlib.

In [12]:
import torch
from torch import nn # nn contains all of PyTorch's building blocks for neural networks
import matplotlib.pyplot as plt

# Check PyTorch version
torch.__version__
Out [12]:
'1.10.0+cu111'

TK - 1. Data (preparing and loading)

I want to stress that "data" in machine learning can be almost anything you can imagine. A table of numbers (like a big Excel spreadsheet), images of any kind, videos (YouTube has lots of data!), audio files like songs or podcasts, protein structures, text and more.

TK - Slide: Machine learning is a game of two parts:

  1. Turn your data, whatever it is, into numbers (a representation).
  2. Pick or build a model to learn the representation as best as possible.

Sometimes one and two can be done at the same time.

But what if you don't have data?

Well, that's where we're at now.

No data.

But we can create some.

Let's create our data as a straight line.

We'll use linear regression to create the data with known parameters (things that can be learned by a model) and then we'll use PyTorch to see if we can build model to estimate these parameters using gradient descent.

Don't worry if the terms above don't mean much now, we'll see them in action and I'll put extra resources below where you can learn more.

In [13]:
# Create *known* parameters
weight = 0.7
bias = 0.3

# Create data
start = 0
end = 1
step = 0.02
X = torch.arange(start, end, step).unsqueeze(dim=1)
y = weight * X + bias

X[:10], y[:10]
Out [13]:
(tensor([[0.0000],
         [0.0200],
         [0.0400],
         [0.0600],
         [0.0800],
         [0.1000],
         [0.1200],
         [0.1400],
         [0.1600],
         [0.1800]]), tensor([[0.3000],
         [0.3140],
         [0.3280],
         [0.3420],
         [0.3560],
         [0.3700],
         [0.3840],
         [0.3980],
         [0.4120],
         [0.4260]]))

Beautiful! Now we're going to move towards building a model that can learn the relationship between X (features) and y (labels).

Split data into training and test sets

We've got some data.

But before we build a model we need to split it up.

One of most important steps in a machine learning project is creating a training and test set (and when required, a validation set).

Each split of the dataset serves a specific purpose:

Split Purpose Amount of total data How often is it used?
Training set The model learns from this data (like the course materials you study during the semester). ~60-80% Always
Validation set The model gets tuned on this data (like the practice exam you take before the final exam). ~10-20% Often but not always
Testing set The model gets evaluated on this data to test what it has learned (like the final exam you take at the end of the semester). ~10-20% Always

For now, we'll just use a training and test set, this means we'll have a dataset for our model to learn on as well as be evaluated on.

We can create them by splitting our X and y tensors.

Note: When dealing with real-world data, this step is typically done right at the start of a project (the test set should always be kept separate from all other data). We want our model to learn on training data and then evaluate it on test data to get an indication of how well it generalizes to unseen examples.

In [14]:
# Create train/test split
train_split = int(0.8 * len(X)) # 80% of data used for training set, 20% for testing 
X_train, y_train = X[:train_split], y[:train_split]
X_test, y_test = X[train_split:], y[train_split:]

len(X_train), len(y_train), len(X_test), len(y_test)
Out [14]:
(40, 40, 10, 10)

Wonderful, we've got 40 samples for training (X_train & y_train) and 10 samples for testing (X_test & y_test).

The model we create is going to try and learn the relationship between X_train & y_train and then we will evaluate what it learns on X_test and y_test.

But right now our data is just numbers on a page.

Let's create a function to visualize it.

In [15]:
def plot_predictions(train_data=X_train, 
                     train_labels=y_train, 
                     test_data=X_test, 
                     test_labels=y_test, 
                     predictions=None):
  """
  Plots training data, test data and compares predictions.
  """
  plt.figure(figsize=(10, 7))

  # Plot training data in blue
  plt.scatter(train_data, train_labels, c="b", s=4, label="Training data")
  
  # Plot test data in green
  plt.scatter(test_data, test_labels, c="g", s=4, label="Testing data")

  if predictions is not None:
    # Plot the predictions in red (predictions were made on the test data)
    plt.scatter(test_data, predictions, c="r", s=4, label="Predictions")

  # Show the legend
  plt.legend(prop={"size": 14});
In [16]:
plot_predictions();

Epic!

Now instead of just being numbers on a page, our data is a straight line.

Note: Now's a good time to introduce you to the data explorer's motto... "visualize, visualize, visualize!"

Think of this whenever you're working with data and turning it into numbers, if you can visualize something, it can do wonders for understanding.

Machines love numbers and we humans like numbers too but we also like to look at things.

TK - 2. Build model

Now we've got some data, let's build a model to use the blue dots to predict the green dots.

We're going to jump right in.

We'll write the code first and then explain everything.

Let's replicate a standard linear regression model using pure PyTorch.

In [17]:
# Create a Linear Regression model class
class LinearRegressionModel(nn.Module): # <- almost everything in PyTorch is a nn.Module (think of this as neural network lego blocks)
    def __init__(self):
        super().__init__() 
        self.weights = nn.Parameter(torch.randn(1, # <- start with random weights (this will get adjusted as the model learns)
            requires_grad=True, # <- can we update this value with gradient descent?
            dtype=torch.float # <- PyTorch loves float32 by default
        ))

        self.bias = nn.Parameter(torch.randn(1, # <- start with random bias (this will get adjusted as the model learns)
            requires_grad=True, # <- can we update this value with gradient descent?
            dtype=torch.float # <- PyTorch loves float32 by default
        ))

    # Forward defines the computation in the model
    def forward(self, x): # <- "x" is the input data (e.g. training/testing features)
        return self.weights * x + self.bias # <- this is the linear regression formula

UPTOHERE: explaining what's happening below

TK - In PyTorch everything to do with models is considered a Module (from nn.Module)...

  • What is nn.Module?
  • What is nn.Parameter? -> read docs
  • What is requires_grad=True?
  • What is a weight? What is a bias? -> linear regression formula
  • What is forward()?

TK - image: add the image from assets (01_linear_regression_model_pytorch) with annoations)

In [18]:
torch.manual_seed(42)
model_0 = LinearRegressionModel()
list(model_0.parameters())
Out [18]:
[Parameter containing:
 tensor([0.3367], requires_grad=True), Parameter containing:
 tensor([0.1288], requires_grad=True)]
In [19]:
# List named parameters 
model_0.state_dict()
Out [19]:
OrderedDict([('weights', tensor([0.3367])), ('bias', tensor([0.1288]))])

We want to start from random parameters and get the model to update them towards parameters that fit our data best (the original weight and bias values).

In [20]:
# Make predictions with model
with torch.inference_mode():
    y_preds = model_0(X_test)
In [21]:
y_preds
Out [21]:
tensor([[0.3982],
        [0.4049],
        [0.4116],
        [0.4184],
        [0.4251],
        [0.4318],
        [0.4386],
        [0.4453],
        [0.4520],
        [0.4588]])
In [22]:
plot_predictions(predictions=y_preds)

Resource: We'll be using Python classes to create bits and pieces for building neural networks. If you're unfamiliar with Python class notation, I'd recommend reading Real Python's Object Orientating programming in Python 3 guide a few times.

Train model

TK - loss function (show graphic for loss function, MAE is distance between the dot points)

In [ ]:
loss_fn = nn.L1Loss() # MAE loss is same as L1Loss
optimizer = torch.optim.SGD(model_0.parameters(), lr=0.01)
In [ ]:
X_test
tensor([[0.8000],
        [0.8200],
        [0.8400],
        [0.8600],
        [0.8800],
        [0.9000],
        [0.9200],
        [0.9400],
        [0.9600],
        [0.9800]])
In [ ]:
torch.manual_seed(42)
epochs = 100
for epoch in range(epochs):
    # Training
    # 1. Forward pass on train data
    y_pred = model_0(X_train)

    # 2. Calculate the loss
    loss = loss_fn(y_pred, y_train)

    # 3. Zero grad of the optimizer
    optimizer.zero_grad()

    # 4. Loss backwards
    loss.backward()

    # 5. Progress the optimizer
    optimizer.step()

    # Testing
    # 1. Forward pass on test data
    with torch.inference_mode():
        test_pred = model_0(X_test)

    # 2. Caculate loss on test data
    test_loss = loss_fn(test_pred, y_test.type(torch.float))

    if epoch % 10 == 0:
        print(f"Epoch: {epoch} | MAE Train Loss: {loss} | MAE Test Loss: {test_loss} ")
Epoch: 0 | MAE Train Loss: 0.31288138031959534 | MAE Test Loss: 0.48106518387794495 
Epoch: 10 | MAE Train Loss: 0.1976713240146637 | MAE Test Loss: 0.3463551998138428 
Epoch: 20 | MAE Train Loss: 0.08908725529909134 | MAE Test Loss: 0.21729660034179688 
Epoch: 30 | MAE Train Loss: 0.053148526698350906 | MAE Test Loss: 0.14464017748832703 
Epoch: 40 | MAE Train Loss: 0.04543796554207802 | MAE Test Loss: 0.11360953003168106 
Epoch: 50 | MAE Train Loss: 0.04167863354086876 | MAE Test Loss: 0.09919948130846024 
Epoch: 60 | MAE Train Loss: 0.03818932920694351 | MAE Test Loss: 0.08886633068323135 
Epoch: 70 | MAE Train Loss: 0.03476089984178543 | MAE Test Loss: 0.0805937647819519 
Epoch: 80 | MAE Train Loss: 0.03132382780313492 | MAE Test Loss: 0.07232122868299484 
Epoch: 90 | MAE Train Loss: 0.02788739837706089 | MAE Test Loss: 0.06473556160926819 
  • TK - plot loss and epochs over time

  • TK - Let's see how close our model gets to the original values for weights and bias

  • This is the whole idea of machine learning and deep learning - there are some ideal values that describe our data, can we train a model to figure them out programmatically...

In [ ]:
model_0.state_dict()
OrderedDict([('weights', tensor([0.5784])), ('bias', tensor([0.3513]))])
In [ ]:
weight, bias
(0.7, 0.3)

TK - Making predictions

Notes:

  • When making predictions or using model in inference mode, use model.eval()
  • When making predictions, use with torch.inference_mode(): context manager
  • All predictions and calculations should be made on same device (e.g. on GPU or on CPU only)
In [ ]:
model_0.eval()
with torch.inference_mode():
    y_preds = model_0(X_test)
y_preds
tensor([[0.8141],
        [0.8256],
        [0.8372],
        [0.8488],
        [0.8603],
        [0.8719],
        [0.8835],
        [0.8950],
        [0.9066],
        [0.9182]])
In [ ]:
plot_predictions(predictions=y_preds)

TK 5. Saving and loading a model

See here for more: https://pytorch.org/tutorials/beginner/saving_loading_models.html

  • 3 core functions to be aware of when saving and loading models in PyTorch:

    1. torch.save - Saves a serialized object to disk. This function uses Python's pickle utility for serialization. Models, tensors and dictionaries of all kinds of objects can be saved using this function.
    2. torch.load - Uses pickle's unpickling facilities to deserialize pickled object files to memory. This function also facilitates the device to load the data into (if you're using a different device you might want to use a different way of saving things).
    3. torch.nn.Module.load_state_dict: Loads a model's parameter dictionary using a deserialized state_dict.
  • TK - path_to_my_model.pth, it's common to use .pt or .pth as a file extension when saving PyTorch models.

Save model

In [ ]:
# Save to file
import os
os.makedirs("models", exist_ok=True)
save_path = "models/01_pytorch_workflow_model_0.pth"
torch.save(model_0.state_dict(), save_path) # only saving the state_dict() only saves the models learned parameters
In [ ]:
!ls -l models/01_pytorch_workflow_model_0.pth
-rw-rw-r-- 1 daniel daniel 1063 Oct 26 12:47 models/01_pytorch_workflow_model_0.pth

Load model

In [ ]:
# Instantiate model
loaded_model_0 = LinearRegressionModel()
loaded_model_0.load_state_dict(torch.load(save_path))
<All keys matched successfully>
In [ ]:
# Evaluate loaded model
loaded_model_0.eval()
with torch.inference_mode():
    loaded_model_preds = loaded_model_0(X_test)
In [ ]:
y_preds == loaded_model_preds
tensor([[True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True]])

TK - 6. Putting it all together

TODO:

  • replicate the above but running on GPU (create data etc)
  • device agnostic code (put model on GPU + data on GPU)
    • won't see much speed up for smaller models but larger models yes
In [ ]:
# Setup device agnostic code
device = "cuda" if torch.cuda.is_available() else "cpu"
device
'cuda'
In [ ]:
# Check which device model is on
next(model_0.parameters()).device
device(type='cpu')

TK - Data

In [ ]:
weight = 0.7
bias = 0.3
start = 0
end = 1
step = 0.02

X = torch.arange(start, end, step).unsqueeze(dim=1) # without unsqueeze, errors will happen later on (shapes within linear layers)
y = weight * X + bias 
X[:10], y[:10]
(tensor([[0.0000],
         [0.0200],
         [0.0400],
         [0.0600],
         [0.0800],
         [0.1000],
         [0.1200],
         [0.1400],
         [0.1600],
         [0.1800]]),
 tensor([[0.3000],
         [0.3140],
         [0.3280],
         [0.3420],
         [0.3560],
         [0.3700],
         [0.3840],
         [0.3980],
         [0.4120],
         [0.4260]]))
In [ ]:
# Split data
train_split = int(0.8 * len(X))
X_train, y_train = X[:train_split], y[:train_split]
X_test, y_test = X[train_split:], y[train_split:]

len(X_train), len(y_train), len(X_test), len(y_test)
(40, 40, 10, 10)
In [ ]:
plot_predictions(X_train, y_train, X_test, y_test)

TK - Building a model

  • This time use nn.Linear()
In [ ]:
class LinearRegressionModelV2(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear_layer = nn.Linear(in_features=1, 
                                      out_features=1)
    
    def forward(self, x):
        return self.linear_layer(x)

torch.manual_seed(42)
model_1 = LinearRegressionModelV2()
model_1, model_1.state_dict()
(LinearRegressionModelV2(
   (linear_layer): Linear(in_features=1, out_features=1, bias=True)
 ),
 OrderedDict([('linear_layer.weight', tensor([[0.7645]])),
              ('linear_layer.bias', tensor([0.8300]))]))

TK - Training

In [ ]:
# Check model device
next(model_1.parameters()).device
device(type='cpu')
In [ ]:
device = "cuda" if torch.cuda.is_available() else "cpu"
model_1.to(device)
next(model_1.parameters()).device
device(type='cuda', index=0)

If model is on GPU, data has to be on GPU...

In [ ]:
loss_fn = nn.L1Loss()
optimizer = torch.optim.SGD(params=model_1.parameters(), lr=0.01)
In [ ]:
torch.manual_seed(42)
epochs = 1000
for epoch in range(epochs):
    # Without this, error will happen (not all model/data on device)
    X_train = X_train.to(device)
    X_test = X_test.to(device)
    y_train = y_train.to(device)
    y_test = y_test.to(device)

    # Training
    model_1.train() # train mode is on by default after construction
    # 1. Forward pass
    y_pred = model_1(X_train)

    # 2. Calculate loss
    loss = loss_fn(y_pred, y_train)

    # 3. Zero grad optimizer
    optimizer.zero_grad()

    # 4. Loss backward
    loss.backward()

    # 5. Step the optimizer
    optimizer.step()

    # Testing
    model_1.eval()
    # 1. Forward pass
    with torch.inference_mode():
        test_pred = model_1(X_test)
    
        # 2. Calculate the loss
        test_loss = loss_fn(test_pred, y_test)

    if epoch % 100 == 0:
        print(f"Epoch: {epoch} | Train loss: {loss} | Test loss: {test_loss}")
Epoch: 0 | Train loss: 0.5551779866218567 | Test loss: 0.5739762187004089
Epoch: 100 | Train loss: 0.006215683650225401 | Test loss: 0.014086711220443249
Epoch: 200 | Train loss: 0.0012645035749301314 | Test loss: 0.013801801018416882
Epoch: 300 | Train loss: 0.0012645035749301314 | Test loss: 0.013801801018416882
Epoch: 400 | Train loss: 0.0012645035749301314 | Test loss: 0.013801801018416882
Epoch: 500 | Train loss: 0.0012645035749301314 | Test loss: 0.013801801018416882
Epoch: 600 | Train loss: 0.0012645035749301314 | Test loss: 0.013801801018416882
Epoch: 700 | Train loss: 0.0012645035749301314 | Test loss: 0.013801801018416882
Epoch: 800 | Train loss: 0.0012645035749301314 | Test loss: 0.013801801018416882
Epoch: 900 | Train loss: 0.0012645035749301314 | Test loss: 0.013801801018416882
In [ ]:
model_1.state_dict()
OrderedDict([('linear_layer.weight', tensor([[0.6968]], device='cuda:0')),
             ('linear_layer.bias', tensor([0.3025], device='cuda:0'))])
In [ ]:
weight, bias
(0.7, 0.3)

TK - Making predictions

In [ ]:
model_1.eval()
with torch.inference_mode():
    y_preds = model_1(X_test)
y_preds
tensor([[0.8600],
        [0.8739],
        [0.8878],
        [0.9018],
        [0.9157],
        [0.9296],
        [0.9436],
        [0.9575],
        [0.9714],
        [0.9854]], device='cuda:0')
In [ ]:
# plot_predictions(predictions=y_preds) # -> won't work... data not on CPU
plot_predictions(predictions=y_preds.cpu())

TK - you're going to get different values whether the model was computed on CPU and or GPU

TK - Saving and loading a model

In [ ]:
# Save model
os.makedirs("models", exist_ok=True)
save_path = "models/01_pytorch_workflow_model_1.pth"
torch.save(model_1.state_dict(), save_path)
In [ ]:
# Load model (if your data is on GPU, model will have to be on GPU to make predictions)
loaded_model_1 = LinearRegressionModelV2()
loaded_model_1.load_state_dict(torch.load(save_path))
loaded_model_1.to(device)
loaded_model_1, next(loaded_model_1.parameters()).device
(LinearRegressionModelV2(
   (linear_layer): Linear(in_features=1, out_features=1, bias=True)
 ),
 device(type='cuda', index=0))
In [ ]:
# Evaluate loaded model
loaded_model_1.eval()
with torch.inference_mode():
    loaded_model_1_preds = loaded_model_1(X_test)
y_preds == loaded_model_1_preds
tensor([[True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True]], device='cuda:0')