-
Notifications
You must be signed in to change notification settings - Fork 1
/
eval_ood.py
188 lines (153 loc) · 7.94 KB
/
eval_ood.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
from __future__ import print_function
import torch
from torch.autograd import Variable
import numpy as np
import pandas as pd
import os
import sys
import time
import argparse
import re
from utils import setup_seed
from utils import get_model
from utils import Logger
from utils import AverageMeter, accuracy
from utils_ood import make_id_ood
from utils_ood import iterate_data_msp
from utils_ood import iterate_data_energy
from utils_ood import iterate_data_odin
from utils_ood import iterate_data_mahalanobis
from utils_ood import iterate_data_rankfeat
from utils_ood import iterate_data_gradnorm
from utils_ood import get_measures
from sklearn.linear_model import LogisticRegressionCV
# from utils_mahalanobis.mahalanobis_lib import get_Mahalanobis_score
# ======== fix data type ========
torch.set_default_tensor_type(torch.FloatTensor)
# ======== options ==============
parser = argparse.ArgumentParser(description='Evaluation on clean samples')
# -------- file param. --------------
parser.add_argument('--data_dir',type=str,default='./data/CIFAR10/',help='data directory')
parser.add_argument('--logs_dir',type=str,default='./logs/',help='logs directory')
parser.add_argument('--dataset',type=str,default='CIFAR10',help='data set name')
parser.add_argument('--model_path',type=str,default='./save/CIFAR10-VGG.pth',help='saved model path')
# -------- hyper param. --------
parser.add_argument('--arch',type=str,default='vgg16',help='model architecture')
parser.add_argument('--seed',type=int,default=0,help='random seeds')
parser.add_argument('--num_classes',type=int,default=10,help='num of classes')
parser.add_argument('--batch_size',type=int,default=256,help='batch size for training (default: 256)')
# -------- ood param. --------
parser.add_argument('--score', choices=['MSP', 'ODIN', 'Energy', 'Mahalanobis', 'GradNorm','RankFeat'], default='MSP')
parser.add_argument('--in_data', choices=['CIFAR10', 'ImageNet'], default='CIFAR10')
parser.add_argument('--in_datadir', type=str, help='in data dir')
parser.add_argument('--out_data', choices=['SVHN','LSUN','iSUN','Texture','places365','iNaturalist','SUN','Places'], default='SVHN')
parser.add_argument('--out_datadir', type=str, help='out data dir')
# --------
parser.add_argument('--temperature_energy', default=1, type=int, help='temperature scaling for energy')
parser.add_argument('--temperature_odin', default=1000, type=int, help='temperature scaling for odin')
parser.add_argument('--epsilon_odin', default=0.0014, type=float, help='perturbation magnitude for odin')
parser.add_argument('--mahalanobis_param_path', default='utils_mahalanobis/logs/', help='path to tuned mahalanobis parameters')
parser.add_argument('--temperature_rankfeat', default=1, type=float, help='temperature scaling for RankFeat')
parser.add_argument('--temperature_gradnorm', default=1, type=float, help='temperature scaling for GradNorm')
args = parser.parse_args()
# ======== log writer init. ========
args.dataset = args.in_data
hyperparam=os.path.split(os.path.split(args.model_path)[-2])[-1]+'-%s'%args.score
if not os.path.exists(os.path.join(args.logs_dir,args.dataset,args.arch,'eval')):
os.makedirs(os.path.join(args.logs_dir,args.dataset,args.arch,'eval'))
args.logs_path = os.path.join(args.logs_dir,args.dataset,args.arch,'eval',hyperparam+'-ood.log')
sys.stdout = Logger(filename=args.logs_path,stream=sys.stdout)
# -------- main function
def main():
# ======== fix random seed ========
setup_seed(args.seed)
if args.score == 'GradNorm':
args.batch_size = 1
# ======== get data set =============
in_set, out_set, in_loader, out_loader = make_id_ood(args)
print('-------- DATA INFOMATION --------')
print('---- in-data : '+args.in_data)
print('---- out-data: '+args.out_data)
# ======== load network ========
checkpoint = torch.load(args.model_path, map_location=torch.device("cpu"))
net = get_model(args).cuda()
net.load_state_dict(checkpoint['state_dict'])
print('-------- MODEL INFORMATION --------')
print('---- arch.: '+args.arch)
print('---- saved path: '+args.model_path)
print('---- inf. seed.: '+str(args.seed))
# ======== evaluation on Ood ========
print('Running %s...'%args.score)
start_time = time.time()
val(net, in_loader, out_loader, args)
duration = time.time() - start_time
print("Finished. Total running time: {}".format(duration))
print()
return
def val(net, in_loader, out_loader, args):
net.eval()
if args.score == 'MSP':
print("Processing in-distribution data...")
in_scores = iterate_data_msp(in_loader, net)
print("Processing out-of-distribution data...")
out_scores = iterate_data_msp(out_loader, net)
elif args.score == 'Energy':
print("Processing in-distribution data...")
in_scores = iterate_data_energy(in_loader, net, args.temperature_energy)
print("Processing out-of-distribution data...")
out_scores = iterate_data_energy(out_loader, net, args.temperature_energy)
elif args.score == 'ODIN':
if args.in_data == 'ImageNet':
args.epsilon_odin = 0.0
print("Processing in-distribution data...")
in_scores = iterate_data_odin(in_loader, net, args.epsilon_odin, args.temperature_odin)
print("Processing out-of-distribution data...")
out_scores = iterate_data_odin(out_loader, net, args.epsilon_odin, args.temperature_odin)
elif args.score == 'RankFeat':
print("Processing in-distribution data...")
in_scores = iterate_data_rankfeat(in_loader, net, args)
print("Processing out-of-distribution data...")
out_scores = iterate_data_rankfeat(out_loader, net, args)
elif args.score == 'GradNorm':
print("Processing in-distribution data...")
in_scores = iterate_data_gradnorm(in_loader, net, args)
print("Processing out-of-distribution data...")
out_scores = iterate_data_gradnorm(out_loader, net, args)
elif args.score == 'Mahalanobis':
hyperparam=os.path.split(os.path.split(args.model_path)[-2])[-1]
sample_mean, precision, lr_weights, lr_bias, magnitude = np.load(
os.path.join(args.mahalanobis_param_path, args.in_data, args.arch, hyperparam, 'results.npy'), allow_pickle=True)
sample_mean = [s.cuda() for s in sample_mean]
precision = [p.cuda() for p in precision]
regressor = LogisticRegressionCV(cv=2).fit([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]], [0, 0, 1, 1])
regressor.coef_ = lr_weights
regressor.intercept_ = lr_bias
# print("lr_weights.shape: ", lr_weights.shape)
# print("lr_bias.shape: ", lr_bias.shape)
if args.in_data == 'CIFAR10':
temp_x = torch.rand(2, 3, 32, 32)
temp_x = Variable(temp_x).cuda()
temp_list = net.feature_list(temp_x)[1]
elif args.in_data == 'ImageNet':
temp_x = torch.rand(2, 3, 224, 224)
temp_x = Variable(temp_x).cuda()
temp_list = net.module.feature_list(temp_x)[1]
num_output = len(temp_list)
print("Processing in-distribution data...")
in_scores = iterate_data_mahalanobis(in_loader, net, args.num_classes, sample_mean, precision,
num_output, magnitude, regressor)
print("Processing out-of-distribution data...")
out_scores = iterate_data_mahalanobis(out_loader, net, args.num_classes, sample_mean, precision,
num_output, magnitude, regressor)
in_examples = in_scores.reshape((-1,1))
out_examples = out_scores.reshape((-1,1))
auroc, aupr_in, aupr_out, fpr95 = get_measures(in_examples, out_examples)
print('============Results for {}============'.format(args.score))
print('AUROC: {}'.format(auroc))
print('AUPR (In): {}'.format(aupr_in))
print('AUPR (Out): {}'.format(aupr_out))
print('FPR95: {}'.format(fpr95))
return
# ======== startpoint
if __name__ == '__main__':
main()