-
Notifications
You must be signed in to change notification settings - Fork 1
/
test.py
131 lines (110 loc) · 3.71 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
126
127
128
129
130
131
import argparse
from functools import partial
import random
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import os
from scood.data import get_dataloader
from scood.evaluation import Evaluator
from scood.networks import ResNet18
from scood.postprocessors import get_postprocessor
from scood.utils import load_yaml
def main(args, config):
benchmark = config["id_dataset"]
if benchmark == "cifar10":
num_classes = 10
num_clusters = 1024
elif benchmark == "cifar100":
num_classes = 100
num_clusters = 2048
# Init Datasets ############################################################
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
set_seed(3407)
get_dataloader_default = partial(
get_dataloader,
root_dir=args.data_dir,
benchmark=benchmark,
num_classes=num_classes,
stage="test",
interpolation=config["interpolation"],
batch_size=config["batch_size"],
shuffle=False,
num_workers=args.prefetch
)
set_seed(3407)
test_id_loader = get_dataloader_default(name=config["id_dataset"])
set_seed(3407)
test_ood_loader_list = []
for name in config["ood_datasets"]:
test_ood_loader = get_dataloader_default(name=name)
test_ood_loader_list.append(test_ood_loader)
set_seed(3407)
net = ResNet18(num_classes=num_classes, dim_aux=num_clusters)
checkpoint = args.checkpoint
if checkpoint:
net.load_state_dict(torch.load(checkpoint), strict=False)
print("Checkpoint Loading Completed!")
net.eval()
if args.ngpu > 1:
net = torch.nn.DataParallel(net, device_ids=list(range(args.ngpu)))
if args.ngpu > 0:
set_seed(3407)
net.cuda()
cudnn.benchmark = True # fire on all cylinders
# #torch.use_deterministic_algorithms(True)
# torch.backends.cudnn.deterministic = True
# torch.backends.cudnn.enabled = False
print("Starting Evaluation...")
postprocess_args = config["postprocess_args"] if config["postprocess_args"] else {}
postprocessor = get_postprocessor(config["postprocess"], **postprocess_args)
set_seed(3407)
evaluator = Evaluator(net)
output_dir = args.csv_path.split('/')
if len(output_dir) >= 3:
output_dir = '/'.join(output_dir[:-1])
else:
output_dir = output_dir[0]
evaluator.eval_ood(
test_id_loader,
test_ood_loader_list,
postprocessor=postprocessor,
method=config["eval_method"],
dataset_type=config["dataset_type"],
csv_path=args.csv_path,
output_dir=output_dir
)
print('Evaluation Completed! Results are saved in "{}"'.format(args.csv_path))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--config",
help="path to config file",
default="configs/test/cifar10.yml",
)
parser.add_argument(
"--checkpoint",
help="path to model checkpoint",
default="output/cifar10/best.ckpt",
)
parser.add_argument(
"--data_dir",
help="directory to dataset",
default="../SCOOD-OT+PASS/data",
)
parser.add_argument(
"--csv_path",
help="path to save evaluation results",
default="results.csv",
)
parser.add_argument("--ngpu", type=int, default=1, help="number of GPUs to use")
parser.add_argument("--prefetch", type=int, default=4, help="pre-fetching threads.")
args = parser.parse_args()
# Load config file
config = load_yaml(args.config)
main(args, config)