Training an Image Classification Model in Pytorch
How to train an image classification model while streaming data from the cloud.

This tutorial is also available as a Colab Notebook​

The primary objective for Hub is to enable users to manage their data more easily so they can train better ML models. This tutorial shows you how to train a simple image classification model while streaming data from a Hub dataset stored in the cloud.

Data Preprocessing

The first step is to select a dataset for training. This tutorial uses the Fashion MNIST dataset that has already been converted into hub format. It is a simple image classification dataset that categorizes images by clothing type (trouser, shirt, etc.)
1
import hub
2
from PIL import Image
3
import numpy as np
4
import os, time
5
import torch
6
from torchvision import datasets, transforms, models
7
​
8
ds_train = hub.load('hub://activeloop/fashion-mnist-train')
9
ds_test = hub.load('hub://activeloop/fashion-mnist-test')
Copied!
The next step is to define a transformation function that will process the data and convert it into a format that can be passed into a deep learning model. The syntax for the transformation function is that the input parameter is a sample from a Hub dataset in dictionary syntax, and the return value is a dictionary containing the data that the training loop uses to train the model. In this particular example, torchvision.transforms is used as a part of the transformation pipeline that performs operations such as normalization and image augmentation (rotation).
1
def transform(sample_in):
2
return {'images': tform(sample_in['images']), 'labels': sample_in['labels']}
3
​
4
tform = transforms.Compose([
5
transforms.ToPILImage(), # Must convert to PIL image for subsequent operations to run
6
transforms.RandomRotation(20), # Image augmentation
7
transforms.ToTensor(), # Must convert to pytorch tensor for subsequent operations to run
8
transforms.Normalize([0.5], [0.5]),
9
])
Copied!
Don't worry if the above syntax is a bit confusing 😡! We're currently improving it.
You are now ready to create a pytorch dataloader that connects the Hub dataset to the PyTorch model. This can be done using the provided method ds.pytorch() , which automatically applies the user-defined transformation function, takes care of random shuffling (if desired), and converts hub data to PyTorch tensors. The num_workers parameter can be used to parallelize data preprocessing, which is critical for ensuring that preprocessing does not bottleneck the overall training workflow.
1
batch_size = 32
2
train_loader = ds_train.pytorch(num_workers = 2, shuffle = True, transform = transform, batch_size = batch_size)
3
test_loader = ds_test.pytorch(num_workers = 2, transform = transform, batch_size = batch_size)
Copied!

Model Definition

This tutorial uses a pre-trained ResNet18 neural network from the torchvision.models module, converted to a single-channel network for grayscale images.
1
# Simple model can be trained on a CPU
2
device = torch.device("cpu")
3
​
4
net = models.resnet18(pretrained=True)
5
# Convert model to grayscale
6
net.conv1 = torch.nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)
7
​
8
# Update the fully connected layer based on the number of classes in the dataset
9
net.fc = torch.nn.Linear(net.fc.in_features, len(ds_train.labels.info.class_names))
10
​
11
net.to(device)
12
​
13
# Specity the loss function and optimizer
14
criterion = torch.nn.CrossEntropyLoss()
15
optimizer = torch.optim.SGD(net.parameters(), lr=0.001, momentum=0.1)
Copied!

Training the Model

Helper functions for training and testing the model are defined. Note that the dictionary that is returned by the transform function in the PyTorch dataloader is access here and is passed into the model.
1
def train_model(loader, test_loader, model, epochs = 1):
2
for epoch in range(epochs): # loop over the dataset multiple times
3
​
4
# Zero the performance stats for each epoch
5
running_loss = 0.0
6
start_time = time.time()
7
total = 0
8
correct = 0
9
10
for i, data in enumerate(loader):
11
# get the inputs; data is a list of [inputs, labels]
12
inputs = data['images']
13
labels = torch.squeeze(data['labels'])
14
​
15
inputs = inputs.to(device)
16
labels = labels.to(device)
17
​
18
# zero the parameter gradients
19
optimizer.zero_grad()
20
​
21
# forward + backward + optimize
22
outputs = model(inputs.float())
23
loss = criterion(outputs, labels)
24
loss.backward()
25
optimizer.step()
26
27
_, predicted = torch.max(outputs.data, 1)
28
total += labels.size(0)
29
correct += (predicted == labels).sum().item()
30
accuracy = 100 * correct / total
31
32
# Print performance statistics
33
running_loss += loss.item()
34
if i % 10 == 0: # print every 10 batches
35
batch_time = time.time()
36
speed = (i+1)/(batch_time-start_time)
37
print('[%d, %5d] loss: %.3f, speed: %.2f, accuracy: %.2f %%' %
38
(epoch + 1, i, running_loss, speed, accuracy))
39
​
40
running_loss = 0.0
41
42
print('Testing Model Performance')
43
test_model(test_loader, model)
44
​
45
print('Finished Training')
46
47
48
def test_model(loader, model):
49
start_time = time.time()
50
total = 0
51
correct = 0
52
with torch.no_grad():
53
for i, data in enumerate(loader):
54
# get the inputs; data is a list of [inputs, labels]
55
inputs = data['images']
56
labels = torch.squeeze(data['labels'])
57
​
58
inputs = inputs.to(device)
59
labels = labels.to(device)
60
​
61
# zero the parameter gradients
62
optimizer.zero_grad()
63
​
64
# forward + backward + optimize
65
outputs = model(inputs.float())
66
​
67
_, predicted = torch.max(outputs.data, 1)
68
total += labels.size(0)
69
correct += (predicted == labels).sum().item()
70
accuracy = 100 * correct / total
71
72
print('Finished Testing')
73
print('Testing accuracy: %.1f %%' %(accuracy))
Copied!
The model and data are ready for training. Let's gooooooooooo πŸš€!
1
train_model(train_loader, test_loader, net, epochs = 1)
Copied!
Congrats! You successfully trained an image classification model while streaming data directly from the cloud! πŸŽ‰
Last modified 8d ago