PyTorch and object-oriented programming

Intermediate Deep Learning with PyTorch

Michal Oleszak

Machine Learning Engineer

What we will learn

How to train robust deep learning models:

  • Improving training with optimizers
  • Mitigating vanishing and exploding gradients
  • Convolutional Neural Networks (CNNs)
  • Recurrent Neural Networks (RNNs)
  • Multi-input and multi-output models

 

 

PyTorch logo

Intermediate Deep Learning with PyTorch

Prerequisites

The course assumes you are comfortable with the following topics:

  • Neural networks training:

    • Forward pass
    • Loss calculation
    • Backward pass (backpropagation)
  • Training models with PyTorch:

    • Datasets and DataLoaders
    • Model training loop
    • Model evaluation
  • Prerequisite course: Introduction to Deep Learning with PyTorch

Intermediate Deep Learning with PyTorch

Object-Oriented Programming (OOP)

  • We will use OOP to define:

    • PyTorch Datasets
    • PyTorch Models
  • In OOP, we create objects with:

    • Abilities (methods)
    • Data (attributes)
Intermediate Deep Learning with PyTorch

Object-Oriented Programming (OOP)

class BankAccount:
    def __init__(self, balance):
        self.balance = balance
  • __init__ is called when BankAccount object is created
  • balance is the attribute of the BankAccount object
account = BankAccount(100)
print(account.balance)
100
Intermediate Deep Learning with PyTorch

Object-Oriented Programming (OOP)

  • Methods: Python functions to perform tasks
  • deposit method increases balance
class BankAccount:
    def __init__(self, balance):
        self.balance = balance


def deposit(self, amount): self.balance += amount
account = BankAccount(100)
account.deposit(50)
print(account.balance)
150
Intermediate Deep Learning with PyTorch

Water potability dataset

Pandas DataFrame showing a couple of first and last rows of the water potability data.

Intermediate Deep Learning with PyTorch

PyTorch Dataset

from torch.utils.data import Dataset

class WaterDataset(Dataset):

def __init__(self, csv_path): super().__init__() df = pd.read_csv(csv_path) self.data = df.to_numpy()
def __len__(self): return self.data.shape[0]
def __getitem__(self, idx): features = self.data[idx, :-1] label = self.data[idx, -1] return features, label
  • init: load data, store as numpy array
    • super().__init__() ensures WaterDataset behaves like torch Dataset
  • len: return the size of the dataset
  • getitem:
    • take one argument called idx
    • return features and label for a single sample at index idx
Intermediate Deep Learning with PyTorch

PyTorch DataLoader

dataset_train = WaterDataset(
    "water_train.csv"
)
from torch.utils.data import DataLoader

dataloader_train = DataLoader(
    dataset_train,
    batch_size=2,
    shuffle=True,
)
features, labels = next(iter(dataloader_train))
print(f"Features: {features},\nLabels: {labels}")
Features: tensor([
  [0.4899, 0.4180, 0.6299, 0.3496, 0.4575,
   0.3615, 0.3259, 0.5011, 0.7545],
  [0.7953, 0.6305, 0.4480, 0.6549, 0.7813,
   0.6566, 0.6340, 0.5493, 0.5789]
]),
Labels: tensor([1., 0.])
Intermediate Deep Learning with PyTorch

PyTorch Model

Sequential model definition:

net = nn.Sequential(
  nn.Linear(9, 16),
  nn.ReLU(),
  nn.Linear(16, 8),
  nn.ReLU(),
  nn.Linear(8, 1),
  nn.Sigmoid(),
)

Class-based model definition:

class Net(nn.Module):

def __init__(self): super().__init__() self.fc1 = nn.Linear(9, 16) self.fc2 = nn.Linear(16, 8) self.fc3 = nn.Linear(8, 1)
def forward(self, x): x = nn.functional.relu(self.fc1(x)) x = nn.functional.relu(self.fc2(x)) x = nn.functional.sigmoid(self.fc3(x)) return x net = Net()
Intermediate Deep Learning with PyTorch

Let's practice!

Intermediate Deep Learning with PyTorch

Preparing Video For Download...