forked from gabbiurlaro/aml22-ego
-
Notifications
You must be signed in to change notification settings - Fork 2
/
save_feat_actionsense.py
182 lines (152 loc) · 8.05 KB
/
save_feat_actionsense.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
import pickle
from utils.logger import logger
import torch.nn.parallel
import torch.optim
import torch
from utils.loaders import EpicKitchensDataset
from utils.args import args
from utils.utils import pformat_dict
import utils
import numpy as np
import os
import models as model_list
import tasks
# global variables among training functions
modalities = None
np.random.seed(13696641)
torch.manual_seed(13696641)
def init_operations():
"""
parse all the arguments, generate the logger, check gpus to be used and wandb
"""
logger.info("Feature Extraction")
logger.info("Running with parameters: " + pformat_dict(args, indent=1))
if args.gpus is not None:
logger.debug('Using only these GPUs: {}'.format(args.gpus))
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpus
def main():
global modalities
init_operations()
modalities = args.modality
print("modalities: ", modalities)
# recover valid paths, domains, classes
# this will output the domain conversion (D1 -> 8, et cetera) and the label list
num_classes, valid_labels, source_domain, target_domain = utils.utils.get_domains_and_labels(args)
print("num_classes: ", num_classes)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
logger.info("Instantiating models per modality")
models = {}
train_augmentations = {}
test_augmentations = {}
for m in modalities:
if m == 'EMG':
logger.info('{} Net\tModality: {}'.format(args.models[m].model, m))
models[m] = getattr(model_list, args.models[m].model)(11)
continue
logger.info('{} Net\tModality: {}'.format(args.models[m].model, m))
models[m] = getattr(model_list, args.models[m].model)(num_classes, m, args.models[m], **args.models[m].kwargs)
train_augmentations[m], test_augmentations[m] = models[m].get_augmentation(m)
action_classifier = tasks.ActionRecognition("action-classifier", models, 1,
args.total_batch, args.models_dir, num_classes,
args.test.num_clips, args.models, args=args)
action_classifier.load_on_gpu(device)
if args.resume_from is not None:
action_classifier.load_last_model(args.resume_from)
if args.action == "save":
augmentations = {"train": train_augmentations, "test": test_augmentations}
# the only action possible with this script is "save"
loader = torch.utils.data.DataLoader(EpicKitchensDataset(args.dataset.shift.split("-")[1], modalities,
args.split, args.dataset,
args.save.num_frames_per_clip,
args.save.num_clips, args.save.dense_sampling,
augmentations[args.split], additional_info=True,
**{"save": args.split}),
batch_size=1, shuffle=False,
num_workers=args.dataset.workers, pin_memory=True, drop_last=False)
save_feat(action_classifier, loader, device, action_classifier.current_iter, num_classes)
else:
raise NotImplementedError
def save_feat(model, loader, device, it, num_classes):
"""
function to validate the model on the test set
model: Task containing the model to be tested
val_loader: dataloader containing the validation data
device: device on which you want to test
it: int, iteration among the training num_iter at which the model is tested
num_classes: int, number of classes in the classification problem
"""
global modalities
model.reset_acc()
model.train(False) # Evaluation mode
results_dict = {"features": []}
num_samples = 0
logits = {}
features = {}
# Iterate over the models
with torch.no_grad():
for i_val, (data, label, video_name, uid) in enumerate(loader):
label = label.to(device)
for m in modalities:
if m == "RGB":
batch, _, height, width = data[m].shape
data[m] = data[m].reshape(batch, args.test.num_clips,
args.test.num_frames_per_clip[m], -1, height, width)
data[m] = data[m].permute(1, 0, 3, 2, 4, 5)
logits[m] = torch.zeros((args.test.num_clips, batch, num_classes)).to(device)
features[m] = torch.zeros((args.test.num_clips, batch, model.task_models[m]
.module.feat_dim)).to(device)
elif m == "EMG":
pass
else:
raise NotImplementedError
clip = {}
for i_c in range(args.test.num_clips):
for m in modalities:
if m == 'EMG':
clip[m] = data[m].to(device)
else:
clip[m] = data[m][i_c].to(device)
output, feat = model(clip)
feat = feat["features"]
for m in modalities:
if m != 'EMG':
#logits[m][i_c] = output[m]
features[m][i_c] = feat[m]
else:
features[m] = feat[m]
for i in range(batch):
sample = {"uid": int(uid[i].cpu().detach().numpy()), "video_name": video_name[i]}
for m in modalities:
if m == 'EMG':
sample["features_" + m] = features[m][0].cpu().detach().numpy() #modificato
else:
sample["features_" + m] = features[m][:, i].cpu().detach().numpy()
results_dict["features"].append(sample)
num_samples += batch
## We don't need accuarcy for saved features (If you uncomment, an exception will be thrown due to unmatching labels range.)
# model.compute_accuracy(logits, label)
# if (i_val + 1) % (len(loader) // 5) == 0:
# logger.info("[{}/{}] top1= {:.3f}% top5 = {:.3f}%".format(i_val + 1, len(loader),
# model.accuracy.avg[1], model.accuracy.avg[5]))
os.makedirs("saved_features", exist_ok=True)
pickle.dump(results_dict, open(os.path.join("saved_features", args.name + "_" +
args.dataset.shift.split("-")[1] + "_" +
args.split + ".pkl"), 'wb'))
#class_accuracies = [(x / y) * 100 for x, y in zip(model.accuracy.correct, model.accuracy.total)]
#logger.info('Final accuracy: top1 = %.2f%%\ttop5 = %.2f%%' % (model.accuracy.avg[1],
# model.accuracy.avg[5]))
#for i_class, class_acc in enumerate(class_accuracies):
# logger.info('Class %d = [%d/%d] = %.2f%%' % (i_class,
# int(model.accuracy.correct[i_class]),
# int(model.accuracy.total[i_class]),
# class_acc))
#logger.info('Accuracy by averaging class accuracies (same weight for each class): {}%'
# .format(np.array(class_accuracies).mean(axis=0)))
#test_results = {'top1': model.accuracy.avg[1], 'top5': model.accuracy.avg[5],
# 'class_accuracies': np.array(class_accuracies)}
#with open(os.path.join(args.log_dir, f'val_precision_{args.dataset.shift.split("-")[0]}-'
# f'{args.dataset.shift.split("-")[-1]}.txt'), 'a+') as f:
# f.write("[%d/%d]\tAcc@top1: %.2f%%\n" % (it, args.train.num_iter, test_results['top1']))
return 'Finished!'
if __name__ == '__main__':
main()