Repository navigation
Expand file tree
/
Copy pathtest.py
More file actions
110 lines (84 loc) · 3.35 KB
/
Copy pathtest.py
File metadata and controls
110 lines (84 loc) · 3.35 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
import os
import sys
import numpy as np
from datetime import datetime
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.optim as optim
from config import args
from data import get_data
from model import get_model
from utils.metrics import Evaluator
from utils.logger import Logger
from utils.utils import set_seeds, set_devices
from utils.loss import get_contrastive_loss
from utils.lr_scheduler import LR_Scheduler
from sklearn.metrics import roc_auc_score
# Get Dataloader, Model
name = args.name
device = set_devices(args)
# Load Data, Create Model
train_loader, val_loader, test_loader = get_data(args)
model = get_model(args, device=device)
nlabels = 4
classifier = nn.Linear(args.embed_size, nlabels).to(device)
# Check if checkpoint exists
ckpt_path = os.path.join(args.dir_result, name, 'ckpts/model.pth'.format(str(args.load_step)))
if not os.path.exists(ckpt_path):
print("invalid checkpoint path : {}".format(ckpt_path))
# Load checkpoint, model
ckpt = torch.load(ckpt_path, map_location=device)
state = ckpt['model']
model.load_state_dict(state)
model.eval()
print('loaded model')
dw_criterion = nn.CrossEntropyLoss()
dw_optimizer = torch.optim.SGD(classifier.parameters(), lr=args.dw_lr)
pbar = tqdm(total=args.dw_epochs, initial=0, bar_format="{desc:<5}{percentage:3.0f}%|{bar:10}{r_bar}")
for epoch in range(1, args.dw_epochs + 1):
loss = 0
classifier.train()
for (idx, train_batch) in enumerate(train_loader):
if args.viewtype in ['clocstime', 'clocslead']:
train_x1, train_x2, train_y, train_group, train_fnames = train_batch
train_x = torch.cat((train_x1, train_x2),dim=0)
train_y = torch.cat((train_y, train_y),dim=0)
train_group = torch.cat((train_group, train_group),dim=0)
else:
train_x, train_y, train_group, train_fnames = train_batch
train_x = train_x.to(device)
dw_pred = classifier(model(train_x))
dw_loss = dw_criterion(dw_pred, train_y.to(torch.long).to(device))
loss += dw_loss
print(f"downstream_loss:{dw_loss}")
dw_optimizer.zero_grad()
dw_loss.backward()
dw_optimizer.step()
if idx % args.log_iter == 0:
tqdm_log = 'downstream_loss: {:.5f}'.format(dw_loss/args.log_iter)
loss = 0
pbar.set_description(tqdm_log)
pbar.update(1)
print("\n Finished training..........Starting Test")
with torch.no_grad():
model.eval()
classifier.eval()
y_pred = []
y_target = []
for (i,test_batch) in enumerate(test_loader):
if args.viewtype in ['clocstime', 'clocslead']:
test_x1, test_x2, test_y, test_group, test_fnames = test_batch
test_x = torch.cat((test_x1, test_x2),dim=0)
test_y = torch.cat((test_y, test_y),dim=0)
test_group = torch.cat((test_group, test_group),dim=0)
else:
test_x, test_y, test_fnames = test_batch
test_x = test_x.to(device)
test_pred = classifier(model(test_x))
y_pred.append(test_pred.cpu())
y_target.append(test_y)
y_pred = torch.cat(y_pred, dim=0).numpy()
y_target = nn.functional.one_hot(torch.cat(y_target,dim=0).to(torch.int64), num_classes=nlabels).numpy()
test_auc = roc_auc_score(y_true=y_target, y_score=y_pred)
print(f"Test AUC:{test_auc}")