Module02 PyTorch
Module02 PyTorch
Deep Learning - I
Applied AI Solutions Developer Program
Module 2
PyTorch
Vejey Gandyer
PyTorch Basics
Simple Neural Network
Tensors
Datasets & Dataloaders
Agenda Transforms
Model Building
Autograds
Optimizer
Serialization
PyTorch Basics
PyTorch
Run PyTorch in a couple of ways:
• In the cloud: Use Colab with a GPU runtime to speed up
operations Runtime > Change runtime type > GPU
• Locally: This option requires to setup PyTorch and TorchVision
first on your local machine (https://pytorch.org/get-started/locally/)
PyTorch Installation (Windows)
PyTorch Installation (Mac)
Simple Neural Network
Simple Neural Network
• Import the necessary libraries
• Download Training and Test data from datasets
• Create Dataloaders
• Define the model
• Linear layer
• ReLU layer
• Define Loss function
• Define Optimizer
• Define Train function
• Define Test function
• Save the trained model
• Load the trained model
• Evaluate the model
PyTorch Tensors
Tensors
• Tensors are a specialized data structure that are very similar to
arrays and matrices. In PyTorch, we use tensors to encode the
inputs and outputs of a model, as well as the model’s
parameters
• Tensors are similar to NumPy’s ndarrays, except that tensors
can run on GPUs or other hardware accelerators
• Tensors and NumPy arrays can often share the same underlying
memory, eliminating the need to copy data
• Tensors are also optimized for automatic differentiation
Tensors
• Initialize the Tensors
• Directly from data
• From a NumPy array
• From a Tensor
• From Random or Constant values
• Attributes of a Tensor
• Shape
• Datatype
• Device
Tensors
• Availability of GPU
• Operations
• Indexing
• Slicing
• Concatenating
• Matrix Multiplication
• Element-wise Multiplication
• NumPy to Tensor
• Tensor to NumPy
Datasets & Dataloaders
Datasets & Dataloaders
• PyTorch provides two data primitives:
• torch.utils.data.DataLoader
• torch.utils.data.Dataset
• Allows to use pre-loaded datasets as well as custom (own) data.
• Dataset stores the samples and their corresponding labels
• DataLoader wraps an iterable around the Dataset to enable easy
access to the samples
Datasets
Load a dataset with the following parameters
• root is the path where the train/test data is stored,
• train specifies training or test dataset,
• download=True downloads the data from the internet if it's not
available at root.
• transform and target_transform specify the feature and label
transformations
Custom Dataset
A custom Dataset class must implement three functions:
• __init__
• __len__
• __getitem__
• torch.randn(5, 3, requires_grad=True)
Autograds
# Backpropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()
if batch % 100 == 0:
loss, current = loss.item(), batch * len(X)
print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
Test Loop
def test_loop(dataloader, model, loss_fn):
size = len(dataloader.dataset)
test_loss, correct = 0, 0
with torch.no_grad():
for X, y in dataloader:
pred = model(X)
test_loss += loss_fn(pred, y).item()
correct += (pred.argmax(1) == y).type(torch.float).sum().item()
test_loss /= size
correct /= size
print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
Epoch
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
epochs = 10
for t in range(epochs):
print(f"Epoch {t+1}\n-------------------------------")
train_loop(train_dataloader, model, loss_fn, optimizer)
test_loop(test_dataloader, model, loss_fn)
print("Training Completed!")
Serialization
Saving & Loading Model parameters
Saving the model parameters
torch.save(model.state_dict(), 'model_weights.pth')
model = models.vgg16()
model.load_state_dict(torch.load('model_weights.pth'))
model.eval()
Saving & Loading Model (Structure +
Parameters)
Saving the model
torch.save(model, 'model.pth')
model = torch.load('model.pth'))
Further Reading
PyTorch
https://pytorch.org/tutorials/
https://uvadlc-notebooks.readthedocs.io/en/latest/tutorial_notebooks/tutorial2/Introduction_to_PyTorch.html