-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.py
222 lines (196 loc) · 9.22 KB
/
validate.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
import torch
import torch.nn as nn
import numpy as np
from tqdm import tqdm
import argparse
import os, sys
import pickle
from termcolor import colored
from sklearn import preprocessing
from DataLoader import VideoQADataLoadertest
import time
from models_cvae import VAE
from config import cfg, cfg_from_file
import ipdb
def validate(cfg, model, data, device):
model.eval()
cos1 = nn.CosineSimilarity(dim=1, eps=1e-6)
le = preprocessing.LabelEncoder()
le.fit(['A','C','F', 'I' ,'R','U'])
accdic = {
'base': [0,0],
'acc': [0,0],
'Aacc': [0,0],
'Cacc': [0,0],
'Iacc': [0,0],
}
all_preds = []
all_answers = []
print('validating...')
with torch.no_grad():
for batch in tqdm(iter(data), total=len(data)):
obj_feat, app_feat, quest, ans, cand_ans, qt, y_idx, n_idx = batch
ans = ans.to(device)
obj_feat = obj_feat.contiguous().view(obj_feat.size(0)*obj_feat.size(1),obj_feat.size(2),obj_feat.size(3))
obj_feat = obj_feat.to(device) # shape T 5 1024
obj_feat_current = obj_feat[:,0,:] # shape T 1 1024
obj_feat_pre = obj_feat[:,1:,:] # shape T 4 1024
# T = obj_feat_current.shape[0]
cand_ans = cand_ans.to(device)
quest = quest.to(device)
#####################################################################
z = torch.zeros(obj_feat_pre.size(0),10).cuda()
x_reconst = model.inference(z,obj_feat_pre) # shape [T 1024]
x_residel = obj_feat_current - x_reconst # shape [T 1024]
dis = torch.linalg.norm(x_residel, dim=1, ord=2)
x_index = torch.argmax(dis.clone().detach())
obj_feat_test = obj_feat_current[x_index]
obj_feat_test = obj_feat_test.unsqueeze(0)
#####################################################################
app_feat = app_feat.to(device)
app_feat = app_feat.reshape(app_feat.shape[0]*app_feat.shape[1]*app_feat.shape[2],app_feat.shape[3])
app_feat_test = torch.mean(app_feat, dim=0)
app_feat_test = torch.unsqueeze(app_feat_test,0)
qt = [*le.inverse_transform(qt.squeeze(0))][0]
if qt in ['A']:
simi = cos1(cand_ans.squeeze(),obj_feat_test+cfg.test.rate*app_feat_test)
predicted = simi.argmax()
elif qt in ['C'] :
simi = cos1(quest,obj_feat_test)
if simi.item() > cfg.test.thr:
indices = y_idx
if len(indices)>=1:
indices_list = torch.cat([*indices]).tolist()
if len(indices_list)==1:
predicted = torch.tensor(indices_list)
else:
simi = cos1(cand_ans.squeeze(),obj_feat_test)
simi[indices_list]+=1
predicted = simi.argmax()
else:
continue
else:
indices = n_idx
if len(indices)>=1:
indices_list = torch.cat([*indices]).tolist()
if len(indices_list)==1:
predicted = torch.tensor(indices_list)
else:
simi = cos1(cand_ans.squeeze(),obj_feat_test)
simi[indices_list]+=1
predicted = simi.argmax()
else:
continue
elif qt in ['I'] :
simi = cos1(quest,obj_feat_test)
if simi.item() > cfg.test.thr:
indices = y_idx
if len(indices)>=1:
indices_list = torch.cat([*indices]).tolist()
if len(indices_list)==1:
predicted = torch.tensor(indices_list)
else:
simi = cos1(cand_ans.squeeze(),obj_feat_test)
simi[indices_list]+=1
predicted = simi.argmax()
else:
continue
else:
indices = n_idx
if len(indices)>=1:
indices_list = torch.cat([*indices]).tolist()
if len(indices_list)==1:
predicted = torch.tensor(indices_list)
else:
simi = cos1(cand_ans.squeeze(),obj_feat_test)
simi[indices_list]+=1
predicted = simi.argmax()
else:
continue
else:
continue
predicted = predicted.to(device)
#True answer and accuracy calcualtions
all_preds.append(predicted)
all_answers.append(ans.squeeze())
if qt in ['A','C','I' ]:
accdic['acc'][0] = accdic['acc'][0]+ (predicted==ans).cpu().numpy()
accdic['acc'][1] = accdic['acc'][1]+ 1
accdic[qt + 'acc'][0] = accdic[qt +'acc'][0]+ (predicted==ans).cpu().numpy()
accdic[qt +'acc'][1] = accdic[qt +'acc'][1]+ 1
acc = accdic['acc'][0]/ accdic['acc'][1]
Aacc = accdic['Aacc'][0]/ accdic['Aacc'][1]
Cacc = accdic['Cacc'][0]/ accdic['Cacc'][1]
Iacc = accdic['Iacc'][0]/ accdic['Iacc'][1]
return accdic, acc, Aacc, Cacc, Iacc
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default='configs/sutd-traffic_transition.yml', type=str)
parser.add_argument('--exp_name', type=str, default='llcp', help='specify experiment name')
parser.add_argument('--layer_size', type=int, default=256, help='specify layer size')
parser.add_argument('--latent_size', type=int, default=10, help='specify latent size')
parser.add_argument('--colatent_size', type=int, default=16, help='specify condition latent size')
args = parser.parse_args()
if args.cfg_file is not None:
cfg_from_file(args.cfg_file)
# load trained model
device = 'cuda' if torch.cuda.is_available() else 'cpu'
cfg.dataset.save_dir = os.path.join(cfg.dataset.save_dir, args.exp_name+'_layer_size'+str(args.layer_size)+'_latent_size'+str(args.latent_size)+'_colatent_size'+str(args.colatent_size))
ckpt = os.path.join(cfg.dataset.save_dir, 'ckpt', 'model_cvae49.pt')
assert os.path.exists(ckpt)
loaded = torch.load(ckpt, map_location='cpu')
latent_layer_size = args.layer_size
latent_size = args.latent_size
con_latent_size = args.colatent_size
model = VAE(
encoder_layer_sizes=[1024, latent_layer_size],
latent_size=latent_size,
decoder_layer_sizes=[latent_layer_size, 1024],
con_encoder_layer_sizes=[1024,latent_layer_size],
con_latent_size=con_latent_size
).to(device)
model.load_state_dict(loaded['state_dict'])
test_loader_kwargs = {
'question_pt': cfg.dataset.test_question_pt,
'appearance_feat': cfg.dataset.appearance_feat,
'object_feat': cfg.dataset.test_object_feat,
'batch_size': 1,
'num_workers': cfg.num_workers,
'shuffle': False
}
test_loader = VideoQADataLoadertest(**test_loader_kwargs)
accdic, acc, accA, accC, accI = validate(cfg, model, test_loader,device)
count = accdic['acc'][1]
sys.stdout.write('~~~~~~ Test Accuracy: {test_acc}, counts:{count} ~~~~~~~\n'.format(
test_acc=colored("{:.4f}".format(acc.item()), "red", attrs=['bold']),
count=colored("{:.4f}".format(count), "red", attrs=['bold'])))
sys.stdout.flush()
count = accdic['Aacc'][1]
sys.stdout.write('~~~~~~ Attribution Test Accuracy: {test_acc}, counts:{count} ~~~~~~~\n'.format(
test_acc=colored("{:.4f}".format(accA.item()), "red", attrs=['bold']),
count=colored("{:.4f}".format(count), "red", attrs=['bold'])))
sys.stdout.flush()
count = accdic['Cacc'][1]
sys.stdout.write('~~~~~~ Counterfactual Test Accuracy: {test_acc}, counts:{count} ~~~~~~~\n'.format(
test_acc=colored("{:.4f}".format(accC.item()), "red", attrs=['bold']),
count=colored("{:.4f}".format(count), "red", attrs=['bold'])))
sys.stdout.flush()
count = accdic['Iacc'][1]
sys.stdout.write('~~~~~~ Introspection Test Accuracy: {test_acc}, counts:{count} ~~~~~~~\n'.format(
test_acc=colored("{:.4f}".format(accI.item()), "red", attrs=['bold']),
count=colored("{:.4f}".format(count), "red", attrs=['bold'])))
sys.stdout.flush()
save_dic = {
'acc': [acc,accdic['acc'][0],accdic['acc'][1]],
'accA': [accA,accdic['Aacc'][0],accdic['Aacc'][1]],
'accC': [accC,accdic['Cacc'][0],accdic['Cacc'][1]],
'accI': [accI,accdic['Iacc'][0],accdic['Iacc'][1]],
}
ipdb.set_trace()
timestr = time.strftime("%Y%m%d-%H%M%S")
path_log = 'accuracies'+timestr
if not os.path.exists(path_log):
os.makedirs(path_log)
path = os.path.join('accuracies'+timestr,f'_accdictionary.pkl')
with open(path , 'wb') as f:
pickle.dump(save_dic, f)