-
Notifications
You must be signed in to change notification settings - Fork 1
/
hpo.py
188 lines (147 loc) · 7.37 KB
/
hpo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/env python
# coding: utf-8
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.models as models
import torchvision.transforms as transforms
from torchvision import datasets, transforms, models
from collections import OrderedDict
import argparse
import os
import logging
import sys
from tqdm import tqdm
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler(sys.stdout))
def test(model, test_loader, criterion, device):
model.eval() # for testing using evalualion function
running_loss=0 # assign running loss
running_corrects=0 # assign running corrects
for inputs, labels in test_loader:
inputs = inputs.to(device)
labels = labels.to(device)
outputs=model(inputs)
loss=criterion(outputs, labels)
_, preds = torch.max(outputs, 1)
running_loss += loss.item() * inputs.size(0) # calculate running loss
running_corrects += torch.sum(preds == labels.data) # calculate running corrects
total_loss = running_loss // len(test_loader)
total_acc = running_corrects.double() // len(test_loader)
logger.info(f"Testing Loss: {total_loss}")
logger.info(f"Testing Accuracy: {total_acc}") # print the loss and accuracy values
def train(model, train_loader, validation_loader, loss_criterion, optimizer, device):
loss_counter=0
best_loss=1e6
epochs = 50
image_dataset={'train':train_loader, 'valid':validation_loader}
for epoch in range(epochs):
logger.info(f"Epoch:{epoch}")
for phase in ['train', 'valid']:
if phase == 'train':
model.train()
else:
model.eval()
running_loss = 0.0
running_corrects = 0
for inputs, labels in image_dataset[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
outputs = model(inputs)
loss = loss_criterion(outputs, labels)
if phase == 'train':
optimizer.zero_grad()
loss.backward()
optimizer.step()
_, preds = torch.max(outputs, 1)
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
epoch_loss = running_loss // len(image_dataset[phase])
epoch_acc = running_corrects // len(image_dataset[phase])
if phase=='valid':
if epoch_loss<best_loss:
best_loss=epoch_loss
else:
loss_counter+=1
logger.info('{} loss: {:.4f}, acc: {:.4f}, best loss: {:.4f}'.format(phase,
epoch_loss,
epoch_acc,
best_loss))
if loss_counter==1:
break
if epoch==0:
break
return model
def net():
model = models.resnet34(pretrained=True) # using the pretrained resnet34 model with 34 layers
for param in model.parameters():
param.requires_grad = False # freeze the model
nfeatures = model.fc.in_features
model.fc = nn.Sequential(
nn.Linear(nfeatures, 512),
nn.ReLU(inplace = True),
nn.Linear(512, 256), # adding own NN layers to the output of the pretrained model
nn.ReLU(inplace=True),
nn.Linear(256, 133)) # output should be 133 as we have 133 classes of dog breeds
return model
def create_data_loaders(data, batch_size):
train_data_path = os.path.join(data, 'train') # Calling OS Environment variable and split it into 3 sets
test_data_path = os.path.join(data, 'test')
validation_data_path=os.path.join(data, 'valid')
train_transform = transforms.Compose([
transforms.RandomResizedCrop((224, 224)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
]) # transforming the training image data
test_transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
]) # transforming the testing image data
# loading train,test & validation data from S3 location using torchvision datasets' Imagefolder function
train_data = torchvision.datasets.ImageFolder(root=train_data_path, transform=train_transform)
train_data_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True)
test_data = torchvision.datasets.ImageFolder(root=test_data_path, transform=test_transform)
test_data_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size)
validation_data = torchvision.datasets.ImageFolder(root=validation_data_path, transform=test_transform)
validation_data_loader = torch.utils.data.DataLoader(validation_data, batch_size=batch_size)
return train_data_loader, test_data_loader, validation_data_loader
def main(args): # args to use with jypyter notebook's Estimater function
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(f"Running on Device {device}")
logger.info(f'Hyperparameters are LR: {args.lr}, Batch Size: {args.batch_size}')
logger.info(f'Data Paths: {args.data}')
train_loader, test_loader, validation_loader=create_data_loaders(args.data, args.batch_size)
model=net() # Initialize a model by calling the net function
model=model.to(device)
loss_criterion = nn.CrossEntropyLoss(ignore_index=133) # using cross Entropy loss function
optimizer = optim.Adam(model.fc.parameters(), lr=args.lr) #using adam optimizer
logger.info("Start Model Training")
model=train(model, train_loader, validation_loader, loss_criterion, optimizer, device) # calling the train function to start the training
logger.info("Testing Model")
test(model, test_loader, loss_criterion, device) # testing model
logger.info("Saving Model")
torch.save(model.state_dict(), os.path.join(args.model_dir, "model.pth")) # save the trained model to S3
if __name__ == '__main__':
parser = argparse.ArgumentParser() # adding the args parsers to use with the notebook estimator call
parser.add_argument(
"--batch_size",
type = int,
default = 64,
metavar = "N",
help = "input batch size for training (default: 64)",
)
parser.add_argument(
"--lr", type = float, default = 0.1, metavar = "LR", help = "learning rate (default: 1.0)"
)
# Using sagemaker OS Environ's channels to locate the training data, model dir and output dir to save in S3 bucket.
parser.add_argument('--data', type=str, default=os.environ['SM_CHANNEL_TRAIN'])
parser.add_argument('--model_dir', type=str, default=os.environ['SM_MODEL_DIR'])
parser.add_argument('--output_dir', type=str, default=os.environ['SM_OUTPUT_DATA_DIR'])
args = parser.parse_args()
print(args)
main(args)