-
Notifications
You must be signed in to change notification settings - Fork 0
/
trainer.py
324 lines (259 loc) · 13.4 KB
/
trainer.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import torch
import numpy as np
import os
import gc
import torch.nn as nn
import evaluator
def get_acc(predictions, labels):
# labels.shape[0]*labels.shape[1] is height * width, since we are doing pixel-level classification
return torch.sum(predictions == labels)/(labels.shape[0]*labels.shape[1])
def get_recall(predictions, labels):
# True Positive / all positive
return torch.sum((predictions == labels) * (labels == 1))/torch.sum(labels == 1)
def get_precision(predictions, labels):
# True Positive / preditcted positive
return torch.sum((predictions == labels) * (labels == 1))/torch.sum(predictions == 1)
# This function is used to train the model
# Reference: pytorch official tutorial
# https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
def train(model, loader_train, loader_val, lr=1e-4, num_epochs=10, device='cpu', patience=5, evaluation_interval=None, pos_weight=None):
# initialize lists to store logs of the validation loss and validation accuracy
val_loss_hist = []
val_acc_hist = []
# initialize optimizer with specified learning rate
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
# From documentation: This loss combines a Sigmoid layer and the BCELoss in one single class.
if pos_weight:
loss_fn = nn.BCEWithLogitsLoss(
pos_weight=torch.Tensor(pos_weight).to(device))
else:
loss_fn = nn.BCEWithLogitsLoss()
# early-stopping parameters
param_hist = []
best_n_loss = None
current_patience = patience
# the number of training steps between evaluations
stop_early = False
for e in range(num_epochs):
# set model to training mode
model.train()
# current batch index
batch_num, num_batches = 0, len(loader_train)
batch_acc_train = []
batch_loss_train = []
batch_recall_train = []
batch_precision_train = []
# Training pass
for X_batch, y_batch in loader_train:
# only take the first color channel of mask
y_batch = y_batch[:, 0, :, :]
# flatten the mask image
y_batch = y_batch.reshape(-1, y_batch.shape[-2] * y_batch.shape[-1])
# torch tensor can be loaded to GPU, when applicable
X_batch, y_batch = X_batch.float().to(device), y_batch.to(device)
# reset gradients for the optimizer, need to be done each training step
optimizer.zero_grad()
# output here is logit (before passing through sigmoid)
output = model(X_batch)
# class=1 if logit > 0 is equivalent to class=1 if sigmoid(logit) > 0.5
predictions = torch.where(output > 0, 1, 0)
# loss_fn here is BCEWithLogitsLoss, which again includes the sigmoid layer
batch_loss = loss_fn(output, y_batch.float())
# compute the gradients and take optimization step
batch_loss.backward()
optimizer.step()
batch_acc = get_acc(predictions, y_batch)
batch_recall = get_recall(predictions, y_batch)
batch_precision = get_precision(predictions, y_batch)
batch_acc_train.append(batch_acc.item())
batch_loss_train.append(batch_loss.item())
batch_recall_train.append(batch_recall.item())
batch_precision_train.append(batch_precision.item())
# running average
avg_train_acc = np.mean(batch_acc_train)
avg_train_loss = np.mean(batch_loss_train)
avg_train_recall = np.mean(batch_recall_train)
avg_train_precision = np.mean(batch_precision_train)
print('Training epoch %d batch %d/%d, train loss = %f, train acc = %f, recall = %f, precision = %f'
% (e+1, batch_num+1, num_batches, avg_train_loss,
avg_train_acc, avg_train_recall, avg_train_precision), end='\r')
batch_num += 1
if batch_num % 20 == 0:
del X_batch
del y_batch
torch.cuda.empty_cache()
gc.collect()
if not evaluation_interval:
evaluation_interval = num_batches//2
# evaluate on validation set every 100 epochs, invoke early-stopping as needed (with patience)
if batch_num % evaluation_interval == 0 or batch_num == num_batches:
# evaluate the model
print()
total_loss_val, total_acc_val, total_recall_val, total_precision_val = evaluator.evaluate_model(
model, loader_val, loss_fn, device)
print('validation metrics at epoch %d batch %d: val loss = %f, val acc = %f, val recall = %f, val precision = %f'
% (e+1, batch_num, total_loss_val, total_acc_val, total_recall_val, total_precision_val))
val_loss_hist.append(total_loss_val)
val_acc_hist.append(total_acc_val)
# early stopping with patience
save_path = 'epoch_%d_batch_%d.model' % (e, batch_num)
torch.save(model.state_dict(), save_path)
param_hist.append(save_path)
# only need to keep weights needed for earlystopping
if len(param_hist) > patience+1:
del_path = param_hist.pop(0)
os.remove(del_path) # delete unnecessary state dicts
if best_n_loss and total_loss_val >= best_n_loss:
current_patience -= 1
print('current_patience = %d' % current_patience)
if current_patience == 0:
print('\nstopping early after no validation accuracy improvement in %d steps'
% (patience * evaluation_interval))
best_weights_path = param_hist[-(patience+1)]
# restore to last best weights when stopping early
model.load_state_dict(torch.load(best_weights_path))
stop_early = True
break
# if performance improves, reset patience and best accuracy
else:
current_patience = patience
best_n_loss = total_loss_val
if stop_early:
break
# get epoch-wide training metrics
epoch_loss_train = np.mean(batch_loss_train)
epoch_acc_train = np.mean(batch_acc_train)
print('='*80+'\nEpoch %d/%d train loss = %f, train acc = %f, val loss = %f, val acc = %f'
% (e+1, num_epochs, epoch_loss_train, epoch_acc_train, total_loss_val, total_acc_val))
if device == 'cuda':
torch.cuda.empty_cache() # free gpu memory if loaded to cuda
else:
gc.collect() # free memory if not using cuda
# remove cached weights after stopping and loading best weights (if applicable)
cached_weight_paths = [f for f in os.listdir(
'.') if ('epoch' in f and '.model' in f)]
for p in cached_weight_paths:
os.remove(p)
return (val_loss_hist, val_acc_hist)
# This function is used to train the model
# Reference: pytorch official tutorial
# https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
def finger_train(model, loader_train, loader_val, lr=1e-4, num_epochs=10, device='cpu', patience=5, evaluation_interval=None, pos_weight=None):
# initialize lists to store logs of the validation loss and validation accuracy
val_loss_hist = []
val_acc_hist = []
# initialize optimizer with specified learning rate
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
# From documentation: This loss combines a Sigmoid layer and the BCELoss in one single class.
if pos_weight:
loss_fn = nn.BCEWithLogitsLoss(
pos_weight=torch.Tensor(pos_weight).to(device))
else:
loss_fn = nn.BCEWithLogitsLoss()
# early-stopping parameters
param_hist = []
best_n_loss = None
current_patience = patience
# the number of training steps between evaluations
stop_early = False
for e in range(num_epochs):
# set model to training mode
model.train()
# current batch index
batch_num, num_batches = 0, len(loader_train)
batch_acc_train = []
batch_loss_train = []
batch_recall_train = []
batch_precision_train = []
# Training pass
for X_batch, y_batch in loader_train:
# only take the first color channel of mask
y_batch = y_batch[:, 0, :, :]
# flatten the mask image
y_batch = y_batch.reshape(-1, y_batch.shape[-2] * y_batch.shape[-1])
# torch tensor can be loaded to GPU, when applicable
X_batch, y_batch = X_batch.float().to(device), y_batch.to(device)
# reset gradients for the optimizer, need to be done each training step
optimizer.zero_grad()
# output here is logit (before passing through sigmoid)
output = model(X_batch)
# class=1 if logit > 0 is equivalent to class=1 if sigmoid(logit) > 0.5
predictions = torch.where(output > 0, 1, 0)
# loss_fn here is BCEWithLogitsLoss, which again includes the sigmoid layer
batch_loss = loss_fn(output, y_batch.float())
# compute the gradients and take optimization step
batch_loss.backward()
optimizer.step()
batch_acc = get_acc(predictions, y_batch)
batch_recall = get_recall(predictions, y_batch)
batch_precision = get_precision(predictions, y_batch)
batch_acc_train.append(batch_acc.item())
batch_loss_train.append(batch_loss.item())
batch_recall_train.append(batch_recall.item())
batch_precision_train.append(batch_precision.item())
# running average
avg_train_acc = np.mean(batch_acc_train)
avg_train_loss = np.mean(batch_loss_train)
avg_train_recall = np.mean(batch_recall_train)
avg_train_precision = np.mean(batch_precision_train)
print('Training epoch %d batch %d/%d, train loss = %f, train acc = %f, recall = %f, precision = %f'
% (e+1, batch_num+1, num_batches, avg_train_loss,
avg_train_acc, avg_train_recall, avg_train_precision), end='\r')
batch_num += 1
if batch_num % 20 == 0:
del X_batch
del y_batch
torch.cuda.empty_cache()
gc.collect()
if not evaluation_interval:
evaluation_interval = num_batches//2
# evaluate on validation set every 100 epochs, invoke early-stopping as needed (with patience)
if batch_num % evaluation_interval == 0 or batch_num == num_batches:
# evaluate the model
print()
total_loss_val, total_acc_val, total_recall_val, total_precision_val = evaluator.evaluate_model(
model, loader_val, loss_fn, device)
print('validation metrics at epoch %d batch %d: val loss = %f, val acc = %f, val recall = %f, val precision = %f'
% (e+1, batch_num, total_loss_val, total_acc_val, total_recall_val, total_precision_val))
val_loss_hist.append(total_loss_val)
val_acc_hist.append(total_acc_val)
# early stopping with patience
save_path = 'epoch_%d_batch_%d.model' % (e, batch_num)
torch.save(model.state_dict(), save_path)
param_hist.append(save_path)
# only need to keep weights needed for earlystopping
if len(param_hist) > patience+1:
del_path = param_hist.pop(0)
os.remove(del_path) # delete unnecessary state dicts
if best_n_loss and total_loss_val >= best_n_loss:
current_patience -= 1
print('current_patience = %d' % current_patience)
if current_patience == 0:
print('\nstopping early after no validation accuracy improvement in %d steps'
% (patience * evaluation_interval))
best_weights_path = param_hist[-(patience+1)]
# restore to last best weights when stopping early
model.load_state_dict(torch.load(best_weights_path))
stop_early = True
break
# if performance improves, reset patience and best accuracy
else:
current_patience = patience
best_n_loss = total_loss_val
if stop_early:
break
# get epoch-wide training metrics
epoch_loss_train = np.mean(batch_loss_train)
epoch_acc_train = np.mean(batch_acc_train)
print('='*80+'\nEpoch %d/%d train loss = %f, train acc = %f, val loss = %f, val acc = %f'
% (e+1, num_epochs, epoch_loss_train, epoch_acc_train, total_loss_val, total_acc_val))
if device == 'cuda':
torch.cuda.empty_cache() # free gpu memory if loaded to cuda
else:
gc.collect() # free memory if not using cuda
# remove cached weights after stopping and loading best weights (if applicable)
cached_weight_paths = [f for f in os.listdir(
'.') if ('epoch' in f and '.model' in f)]
for p in cached_weight_paths:
os.remove(p)
return (val_loss_hist, val_acc_hist)