-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
223 lines (178 loc) · 7.38 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
"""
train.py - Standardized NN training script for PyTorch.
"""
import random
import numpy
import torch
import sys
import time
from tqdm import tqdm
from torch.optim.lr_scheduler import ReduceLROnPlateau
def seed_everything(seed: int):
random.seed(seed)
numpy.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
def epoch(model,
loader,
pred_fn,
truth_fn,
loss_fn,
metric,
batch_len,
dataset_len,
device,
optimizer=None):
if optimizer is None:
model.eval()
else:
model.train()
result, loss = 0.0, 0.0
for batch in tqdm(loader):
if optimizer is not None:
optimizer.zero_grad()
batch = batch.to(device)
pred = pred_fn(model, batch).squeeze()
# print(pred)
truth = truth_fn(batch)
batch_loss = loss_fn(pred, truth)
if optimizer is not None:
batch_loss.backward()
optimizer.step()
with torch.no_grad():
loss += batch_loss.item() * batch_len(batch)
result += metric(pred, truth).item() * batch_len(batch)
return loss/dataset_len, result/dataset_len
def run(epochs,
model,
train_loader,
valid_loader,
test_loader,
train_set,
valid_set,
test_set,
pred_fn,
truth_fn,
loss_fn,
metric,
metric_str,
batch_len,
device,
optimizer,
lr_scheduler=None,
choose_best='max',
log_file=sys.stdout):
"""
Parameters:
epochs -- max epochs to train (int)
model -- the model (callable)
train_loader, valid_loader, test_loader -- the train/valid/test loader (iterable)
train_set, valid_set, test_set -- the train/valid/test dataset
pred_fn -- function that takes in `model` & `batch`, and gives an output tensor `pred`
truth_fn -- function that takes in `batch`, and gives an output tensor `truth`
loss_fn -- function that takes in `pred` & `truth`, and computes average loss tensor
metric -- function that takes in `pred` & `truth`, and computes average metric tensor
metric_str -- name of the metric
batch_len -- function that takes in `batch`, and gives its length
device -- the device (str)
optimizer -- the optimizer
lr_scheduler -- the learning rate scheduler (default None)
choose_best -- whether to choose the epoch with best validation performance,
if None then choose the last epoch (default 'max', means that larger metric
is better)
log_file -- file to write log
"""
model.to(device)
best_val_metric = 1e6 if choose_best == 'min' else 0
best_test_metric = 0
before_running = time.time()
for idx in range(epochs):
train_loss, train_metric = epoch(model, train_loader, pred_fn, truth_fn,
loss_fn, metric, batch_len,
len(train_set), device, optimizer)
val_loss, val_metric = epoch(model, valid_loader, pred_fn, truth_fn,
loss_fn, metric, batch_len, len(valid_set),
device, None)
test_loss, test_metric = epoch(model, test_loader, pred_fn, truth_fn,
loss_fn, metric, batch_len, len(test_set),
device, None)
if choose_best == 'max' and val_metric > best_val_metric:
best_val_metric = val_metric
best_test_metric = test_metric
elif choose_best == 'min' and val_metric < best_val_metric:
best_val_metric = val_metric
best_test_metric = test_metric
if lr_scheduler is not None:
if lr_scheduler.__class__ != ReduceLROnPlateau:
lr_scheduler.step()
else:
lr_scheduler.step(val_metric)
if log_file is not None:
print("Epoch %d: " % idx, file=log_file)
print("Training Loss: %f Training %s: %f" % (train_loss, metric_str, train_metric), file=log_file)
print("Validation Loss: %f Validation %s: %f" % (val_loss, metric_str, val_metric), file=log_file)
print("Test Loss %f Test %s: %f" % (test_loss, metric_str, test_metric), file=log_file)
after_running = time.time()
print(f"Running time for {epochs} epochs:", after_running - before_running)
return best_test_metric
@torch.no_grad()
def inference(epochs,
model,
train_loader,
valid_loader,
test_loader,
train_set,
valid_set,
test_set,
pred_fn,
truth_fn,
loss_fn,
metric,
metric_str,
batch_len,
device,
choose_best='max'):
"""
Parameters:
epochs -- max epochs to train (int)
model -- the model (callable)
train_loader, valid_loader, test_loader -- the train/valid/test loader (iterable)
train_set, valid_set, test_set -- the train/valid/test dataset
pred_fn -- function that takes in `model` & `batch`, and gives an output tensor `pred`
truth_fn -- function that takes in `batch`, and gives an output tensor `truth`
loss_fn -- function that takes in `pred` & `truth`, and computes average loss tensor
metric -- function that takes in `pred` & `truth`, and computes average metric tensor
metric_str -- name of the metric
batch_len -- function that takes in `batch`, and gives its length
device -- the device (str)
optimizer -- the optimizer
lr_scheduler -- the learning rate scheduler (default None)
choose_best -- whether to choose the epoch with best validation performance,
if None then choose the last epoch (default 'max', means that larger metric
is better)
log_file -- file to write log
"""
model.to(device)
best_val_metric = 1e6 if choose_best == 'min' else 0
best_test_metric = 0
for idx in range(epochs):
train_loss, train_metric = epoch(model, train_loader, pred_fn, truth_fn,
loss_fn, metric, batch_len,
len(train_set), device, None)
val_loss, val_metric = epoch(model, valid_loader, pred_fn, truth_fn,
loss_fn, metric, batch_len, len(valid_set),
device, None)
test_loss, test_metric = epoch(model, test_loader, pred_fn, truth_fn,
loss_fn, metric, batch_len, len(test_set),
device, None)
if choose_best == 'max' and val_metric > best_val_metric:
best_val_metric = val_metric
best_test_metric = test_metric
elif choose_best == 'min' and val_metric < best_val_metric:
best_val_metric = val_metric
best_test_metric = test_metric
print("Epoch %d: " % idx)
print("Training Loss: %f Training %s: %f" % (train_loss, metric_str, train_metric))
print("Validation Loss: %f Validation %s: %f" % (val_loss, metric_str, val_metric))
print("Test Loss %f Test %s: %f" % (test_loss, metric_str, test_metric))
return best_test_metric