forked from marco-rudolph/AST
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtrain_teacher.py
More file actions
114 lines (90 loc) · 4.36 KB
/
train_teacher.py
File metadata and controls
114 lines (90 loc) · 4.36 KB
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
import time
import numpy as np
import torch
from os.path import join
from sklearn.metrics import roc_auc_score
from tqdm import tqdm
import config as c
from model import *
from utils import *
def train(train_loader, test_loader):
model = Model()
model.to(c.device)
optimizer = torch.optim.Adam(model.net.parameters(), lr=c.lr, eps=1e-08, weight_decay=1e-5)
mean_nll_obs = Score_Observer('AUROC mean over maps')
max_nll_obs = Score_Observer('AUROC max over maps')
batch_limit_warning_printed = False
start = time.time()
train_log_step = 0
test_log_step = 0
for epoch in range(c.meta_epochs):
# train some epochs
model.train()
if c.verbose:
print(F'\nTrain epoch {epoch}')
for sub_epoch in range(c.sub_epochs):
train_loss = list()
for i, data in enumerate(tqdm(train_loader, disable=c.hide_tqdm_bar)):
optimizer.zero_grad()
depth, fg, labels, image, features = data
depth, fg, labels, image, features = to_device([depth, fg, labels, image, features])
fg = dilation(fg, c.dilate_size) if c.dilate_mask else fg
img_in = features if c.pre_extracted else image
fg_down = downsampling(fg, (c.map_len, c.map_len), bin=False)
z, jac = model(img_in, depth)
loss = get_nf_loss(z, jac, fg_down)
train_loss.append(t2np(loss))
loss.backward()
optimizer.step()
if c.sub_epoch_batch_limit > 0 and i > c.sub_epoch_batch_limit:
if not batch_limit_warning_printed:
batch_limit_warning_printed = True
print(f"Batch limit of {c.sub_epoch_batch_limit} used to limit time per sub epoch.")
break
mean_train_loss = np.mean(train_loss)
if "mlflow_tracking_uri" in globals():
mlflow.log_metric(f"{c.class_name}-teacher-train-loss", mean_train_loss, step=train_log_step)
train_log_step += 1
if c.verbose and sub_epoch % c.sub_epoch_log_interval == 0: # and epoch == 0:
print('Epoch: {:d}.{:d} \t train loss: {:.4f} \t ({:d} s runtime)'.format(epoch, sub_epoch, mean_train_loss, int(time.time() - start)))
# evaluate
model.eval()
if c.verbose:
print('\nCompute loss and scores on test set:')
test_loss = list()
test_labels = list()
img_nll = list()
max_nlls = list()
with torch.no_grad():
for i, data in enumerate(tqdm(test_loader, disable=c.hide_tqdm_bar)):
depth, fg, labels, image, features = data
depth, fg, image, features = to_device([depth, fg, image, features])
fg = dilation(fg, c.dilate_size) if c.dilate_mask else fg
img_in = features if c.pre_extracted else image
fg_down = downsampling(fg, (c.map_len, c.map_len), bin=False)
z, jac = model(img_in, depth)
loss = get_nf_loss(z, jac, fg_down, per_sample=True)
nll = get_nf_loss(z, jac, fg_down, per_pixel=True)
img_nll.append(t2np(loss))
max_nlls.append(np.max(t2np(nll), axis=(-1, -2)))
test_loss.append(loss.mean().item())
test_labels.append(labels)
img_nll = np.concatenate(img_nll)
max_nlls = np.concatenate(max_nlls)
test_loss = np.mean(np.array(test_loss))
if "mlflow_tracking_uri" in globals():
mlflow.log_metric(f"{c.class_name}-teacher-test-loss", test_loss, step=test_log_step)
test_log_step += 1
if c.verbose:
print('Epoch: {:d} \t test_loss: {:.4f}'.format(epoch, test_loss))
test_labels = np.concatenate(test_labels)
is_anomaly = np.array([0 if l == 0 else 1 for l in test_labels])
mean_nll_obs.update(roc_auc_score(is_anomaly, img_nll), epoch,
print_score=c.verbose or epoch == c.meta_epochs - 1)
max_nll_obs.update(roc_auc_score(is_anomaly, max_nlls), epoch,
print_score=c.verbose or epoch == c.meta_epochs - 1)
if c.save_model:
save_weights(model, 'teacher')
return mean_nll_obs, max_nll_obs
if __name__ == "__main__":
train_dataset(train, img_aug=True)