-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
125 lines (98 loc) · 4.97 KB
/
test.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
import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__))))
import argparse
import logging
import torch
import numpy as np
from tqdm.auto import tqdm
from models import build_model
from data import build_datamanager
from logger import setup_logging
from utils import read_config, rmdir
from evaluators import recognition_metrics, log_test
def main(config):
cfg_trainer = config['trainer_colab'] if config['colab'] == True else config['trainer']
run_id = config['resume'].split('/')[-2]
file_name = config['resume'].split('/')[-1].split('.')[0]
output_dir = os.path.join(cfg_trainer['output_dir'], run_id, file_name)
(os.path.exists(output_dir) or os.makedirs(output_dir, exist_ok=True)) and rmdir(output_dir, remove_parent=False)
setup_logging(output_dir)
logger = logging.getLogger('test')
use_gpu = cfg_trainer['n_gpu'] > 0 and torch.cuda.is_available()
device = torch.device('cuda:0' if use_gpu else 'cpu')
map_location = "cuda:0" if use_gpu else torch.device('cpu')
datamanager, _ = build_datamanager(config['type'], config['data'])
model, _ = build_model(config, num_classes=len(datamanager.datasource.get_attribute()))
logger.info('Loading checkpoint: {} ...'.format(config['resume']))
checkpoint = torch.load(config['resume'], map_location=map_location)
model.load_state_dict(checkpoint['state_dict'])
model.eval()
model.to(device)
preds = []
labels = []
with tqdm(total=len(datamanager.get_dataloader('test'))) as epoch_pbar:
with torch.no_grad():
for batch_idx, (data, _labels) in enumerate(datamanager.get_dataloader('test')):
data, _labels = data.to(device), _labels.to(device)
out = model(data)
_preds = torch.sigmoid(out)
preds.append(_preds)
labels.append(_labels)
epoch_pbar.update(1)
preds = torch.cat(preds, dim=0)
labels = torch.cat(labels, dim=0)
preds = preds.cpu().numpy()
labels = labels.cpu().numpy()
# # get best threshold
# from sklearn.metrics import roc_curve, auc, precision_recall_curve
# precision = dict()
# recall = dict()
# thresholds_pr = dict()
# pr_auc = dict()
# best_threshold = dict()
# fpr = dict()
# tpr = dict()
# roc_auc = dict()
# thresholds_roc = dict()
# for i in range(len(datamanager.datasource.get_attribute())):
# precision[i], recall[i], thresholds_pr[i] = precision_recall_curve(labels[:, i], preds[:, i])
# pr_auc[i] = auc(recall[i], precision[i])
# best_threshold[i] = np.argmax((2 * precision[i] * recall[i]) / (precision[i] + recall[i]))
# fpr[i], tpr[i], thresholds_roc[i] = roc_curve(labels[:, i], preds[:, i])
# roc_auc[i] = auc(fpr[i], tpr[i])
# fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2)
# ax1.plot(recall[i], precision[i], label='Precision-Recall Curve, mAP: %f' % pr_auc[i])
# ax1.scatter(
# recall[i][best_threshold[i]],
# precision[i][best_threshold[i]],
# marker='o',
# color='black',
# label='Best threshold %f' % (thresholds_pr[i][best_threshold[i]]))
# ax1.set_xlabel('Recall')
# ax1.set_ylabel('Precision')
# ax1.set_title('Attribute: %s' % datamanager.datasource.get_attribute()[i])
# # ax1.legend(loc="lower right")
# fig, ax2 = plt.subplots(122)
# ax2.plot(fpr[i], tpr[i], label='ROC curve (area = %0.2f)' % (roc_auc[i]))
# ax2.plot([0, 1], [0, 1], 'k--')
# ax2.scatter(fpr[i][best_threshold[i]], tpr[i][best_threshold[i]], marker='o', color='black', label='Best threshold %f' % (thresholds[i][best_threshold[i]]))
# ax2.set_xlim([0.0, 1.0])
# ax2.set_ylim([0.0, 1.05])
# ax2.set_xlabel('False Positive Rate')
# ax2.set_ylabel('True Positive Rate')
# ax2.set_title('Attribute: %s' % datamanager.datasource.get_attribute()[i])
# # ax2.legend(loc="lower right")
# plt.show()
result_label, result_instance = recognition_metrics(labels, preds)
log_test(logger.info, datamanager.datasource.get_attribute(), datamanager.datasource.get_weight('test'), result_label, result_instance)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='')
parser.add_argument('--config', default='base/config.json', type=str, help='config file path (default: base/config.json)')
parser.add_argument('--resume', default='', type=str, help='resume file path (default: .)')
parser.add_argument('--colab', default=False, type=lambda x: (str(x).lower() == 'true'), help='train on colab (default: false)')
args = parser.parse_args()
config = read_config(args.config)
config.update({'resume': args.resume})
config.update({'colab': args.colab})
main(config)