-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
252 lines (191 loc) · 10.5 KB
/
train.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# -*- coding: utf-8 -*-
"""
The file contains implementations of the functions used to train a CNN model.
train_cnn - Function used to train a Convolutional Neural Network.
"""
# Built-in/Generic Imports
import os
import time
from argparse import Namespace
# Library Imports
import timm
import torch
from torch.cuda import amp
from torch.nn import functional as F
from torch.utils.data import DataLoader
from torch.optim import SGD, lr_scheduler
# Own Modules
from utils import log
from dataset import get_datasets, Dataset
from calibration import optimise_temperature
from model import CNNClassifier, SWINClassifier
__author__ = ["Jacob Carse", "Tamás Süveges"]
__copyright__ = "Copyright 2022, Dermatology"
__credits__ = ["Jacob Carse", "Tamás Süveges"]
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer = ["Jacob Carse", "Tamás Süveges"]
__email__ = ["j.carse@dundee.ac.uk", "t.suveges@dundee.ac.uk"]
__status__ = "Development"
def train_cnn(arguments: Namespace, device: torch.device, load_model: bool = False,train_data: Dataset = None,
val_data: Dataset = None, fold: int = None) -> float:
"""
Function for training the Convolutional Neural Network.
:param arguments: ArgumentParser Namespace object with arguments used for training.
:param device: PyTorch device that will be used for training.
:param load_model: Boolean if another trained model should be loaded for fine-tuning.
:param train_data: Dataset object to be used to train the model.
:param val_data: Dataset object to be used to validation the model.
:param fold: Integer for the current k_fold if using cross validation.
"""
# Sets PyTorch to detect errors in Autograd, useful for debugging but slows down performance.
if arguments.detect_anomaly:
torch.autograd.set_detect_anomaly(True)
# Loads the training and validation data.
if train_data is None or val_data is None:
train_data, val_data, _ = get_datasets(arguments)
# Creates the training data loader using the dataset object.
training_data_loader = DataLoader(train_data, batch_size=arguments.batch_size,
shuffle=True, num_workers=arguments.data_workers,
pin_memory=False, drop_last=False)
# Creates the validation data loader using the dataset object
validation_data_loader = DataLoader(val_data, batch_size=arguments.batch_size * 2,
shuffle=False, num_workers=arguments.data_workers,
pin_memory=False, drop_last=False)
log(arguments, "Loaded Datasets\n")
# Initialises the classifier model.
if arguments.swin_model:
# Loads the SWIN Transformer model.
classifier = SWINClassifier(train_data.num_classes)
else:
# Loads the EfficientNet CNN model.
classifier = CNNClassifier(arguments.efficient_net, train_data.num_classes)
# Loads a pretrained model if specified.
if load_model:
classifier.load_state_dict(torch.load(os.path.join(arguments.model_dir, f"{arguments.load_model}_best.pt")))
# Sets the classifier to training mode.
classifier.train()
# Moves the classifier to the selected device.
classifier.to(device)
# Initialises the optimiser used to optimise the parameters of the model.
optimiser = SGD(params=classifier.parameters(), lr=arguments.minimum_lr)
# Initialises the learning rate scheduler to adjust the learning rate during training.
step_size = (len(training_data_loader) // arguments.batch_size) * 2
scheduler = lr_scheduler.CyclicLR(optimiser, base_lr=arguments.minimum_lr, max_lr=arguments.maximum_lr, step_size_up=step_size, mode="triangular")
if arguments.precision == 16 and device != torch.device("cpu"):
scaler = amp.GradScaler()
log(arguments, "Model Initialised")
# Declares the main logging variables for training.
start_time = time.time()
best_loss, best_epoch, total_batches = 1e10, 0, 0
# The beginning of the main training loop.
for epoch in range(1, arguments.epochs + 1):
# Declares the logging variables for the epoch.
epoch_acc, epoch_loss, num_batches = 0., 0., 0
# Loops through the training data batches.
for images, labels in training_data_loader:
images = images.to(device)
labels = labels.to(device)
# Resets the gradients in the model.
optimiser.zero_grad()
# Performs training step with 16 bit precision.
if arguments.precision == 16 and device != torch.device("cpu"):
with amp.autocast():
# Performs forward propagation using the CNN model.
predictions = classifier(images)
# Calculates the cross entropy loss.
loss = F.cross_entropy(predictions, labels)
# Clips the gradient to the maximum value of a 16-bit float.
torch.nn.utils.clip_grad_norm_(classifier.parameters(), torch.finfo(torch.float16).max)
# Using the gradient scaler performs backward propagation.
scaler.scale(loss).backward()
# Update the weights of the model using the optimiser.
scaler.step(optimiser)
# Updates the scale factor of the gradient scaler.
scaler.update()
# Performs training step with 32 bit precision.
else:
# Performs forward propagation using the CNN model.
predictions = classifier(images)
# Calculates the cross entropy loss.
loss = F.cross_entropy(predictions, labels)
# Clips the gradient to the maximum value of a 32-bit float.
torch.nn.utils.clip_grad_norm_(classifier.parameters(), torch.finfo().max)
# Performs backward propagation with the loss.
loss.backward()
# Updates the parameters of the model using the optimiser.
optimiser.step()
# Calculates the accuracy of the batch.
batch_accuracy = (predictions.max(dim=1)[1] == labels).sum().double() / labels.shape[0]
# Adds the number of batches, losses and accuracy to the epoch sum.
num_batches += 1
epoch_loss += loss.item()
epoch_acc += batch_accuracy.item()
# Updates the learning rate scheduler.
scheduler.step()
# Logs the details of the epoch progress.
if num_batches % arguments.log_interval == 0:
log(arguments, "Time: {}s\tTrain Epoch: {} [{}/{}] ({:.0f}%)\tLoss: {:.6f}\tAccuracy: {:.6f}".format(
str(int(time.time() - start_time)).rjust(6, '0'), str(epoch).rjust(2, '0'),
str(num_batches * arguments.batch_size).rjust(len(str(len(train_data))), '0'),
len(train_data), 100. * num_batches / (len(train_data) / arguments.batch_size),
epoch_loss / num_batches, epoch_acc / num_batches
))
# If the number of batches have been reached end epoch.
if num_batches == arguments.batches_per_epoch:
break
# Updates the total number of batches (used for debugging).
total_batches += num_batches
# Declares the logging variables for validation.
val_acc, val_loss, val_batches = 0., 0., 0
# Performs the validation epoch with no gradient calculations.
with torch.no_grad():
# Loops through the validation data batches.
for images, labels in validation_data_loader:
# Moves through the validation data batches.
images = images.to(device)
labels = labels.to(device)
# Performs forward propagation using 16 bit precision.
if arguments.precision == 16 and device != torch.device("cpu"):
with amp.autocast():
# Performs forward propagation using the CNN model.
predictions = classifier(images)
# Calculates the cross entropy loss.
loss = F.cross_entropy(predictions, labels)
# Performs forward propagation using 32 bit precision.
else:
# Performs forward propagation using the CNN model.
predictions = classifier(images)
# Calculates the cross entropy loss.
loss = F.cross_entropy(predictions, labels)
# Calculates the accuracy of the batch.
batch_accuracy = (predictions.max(dim=1)[1] == labels).sum().double() / labels.shape[0]
# Adds the number of batches, loss and accuracy to validation sum.
val_batches += 1
val_loss += loss.item()
val_acc += batch_accuracy.item()
# If the number of batches have been reached end validation.
if val_batches == arguments.batches_per_epoch:
break
# Logs the details of the training epoch.
log(arguments, "\nEpoch: {}\tTraining Loss: {:.6f}\tTraining Accuracy: {:.6f}\n"
"Validation Loss: {:.6f}\tValidation Accuracy: {:.6f}\n".format(
epoch, epoch_loss / num_batches, epoch_acc / num_batches, val_loss / val_batches, val_acc / val_batches
))
# If the current epoch has the best validation loss then save the model with the prefix best.
if val_loss / val_batches < best_loss:
best_loss = val_loss / val_batches
best_epoch = epoch
# Checks if the save directory exists and if not creates it.
os.makedirs(arguments.model_dir, exist_ok=True)
# Saves the model to the save directory.
model_name = f"{arguments.experiment}_{'' if fold is None else str(fold)+'_'}best.pt"
torch.save(classifier.state_dict(), os.path.join(arguments.model_dir, model_name))
# Loads the best trained model.
classifier.load_state_dict(torch.load(os.path.join(arguments.model_dir, f"{arguments.experiment}_{'' if fold is None else str(fold)+'_'}best.pt")))
# Logs the final training information.
log(arguments,
f"\nTraining Finished with best loss of {round(best_loss, 4)} at epoch {best_epoch} in "
f"{int(time.time() - start_time)}s.")
temperature = optimise_temperature(arguments, classifier, validation_data_loader, device)
return temperature