-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathevaluate.py
155 lines (117 loc) · 5.19 KB
/
evaluate.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
import os
import numpy as np
import torch
import torch.optim
import torch.utils.data
import argparse
from src.get_data import getData
def main(noise_type='white', data='cifar10', folder=None, batch_size=512):
models = [f for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))]
models = sorted(models)
print('************************')
print(noise_type)
print('************************')
print(models)
_, test_loader = getData(name=data, train_bs=batch_size, test_bs=batch_size)
for index, m in enumerate(models):
model = torch.load(folder + m)
#print("Beginning noisy evaluation")
print(m)
model.eval()
#acc1 = cls_validate(test_loader, model)
if noise_type=='white':
_ = cls_noisy_validate(test_loader, model)
elif noise_type=='sp':
_ = cls_sp_validate(test_loader, model)
def cls_validate(val_loader, model, time_begin=None):
model.eval()
acc1_val = 0
n = 0
with torch.no_grad():
for i, (images, target) in enumerate(val_loader):
images = images.cuda(non_blocking=True)
target = target.cuda(non_blocking=True)
output = model(images)
model_logits = output[0] if (type(output) is tuple) else output
pred = model_logits.data.max(1, keepdim=True)[1] # get the index of the max log-probability
acc1_val += pred.eq(target.data.view_as(pred)).cpu().sum().item()
n += len(images)
avg_acc1 = (acc1_val / n)
return avg_acc1
def cls_noisy_validate(val_loader, model, time_begin=None):
perturbed_test_accs = []
for eps in [0, 0.02, 0.04, 0.06, 0.08, 0.1, 0.12, 0.15, 0.18, 0.2, 0.25, 0.3, 0.35]:
model.eval()
acc1_val = 0
n = 0
with torch.no_grad():
for i, (images, target) in enumerate(val_loader):
images = images.cuda(non_blocking=True)
target = target.cuda(non_blocking=True)
images += eps * torch.cuda.FloatTensor(images.shape).normal_()
output = model(images)
model_logits = output[0] if (type(output) is tuple) else output
pred = model_logits.data.max(1, keepdim=True)[1] # get the index of the max log-probability
acc1_val += pred.eq(target.data.view_as(pred)).cpu().sum().item()
n += len(images)
avg_acc1 = (acc1_val / n)
perturbed_test_accs.append(avg_acc1)
print(perturbed_test_accs)
return perturbed_test_accs
def sp(image, amount):
row, col = image.shape
s_vs_p = 0.5
out = np.copy(image)
# Salt mode
num_salt = np.ceil(amount * image.size * s_vs_p)
idx = np.random.choice(range(32 * 32), np.int(num_salt), False)
out = out.reshape(image.size, -1)
out[idx] = np.min(out)
out = out.reshape(32, 32)
# Pepper mode
num_pepper = np.ceil(amount * image.size * (1. - s_vs_p))
idx = np.random.choice(range(32 * 32), np.int(num_pepper), False)
out = out.reshape(image.size, -1)
out[idx] = np.max(out)
out = out.reshape(32, 32)
return out
def sp_wrapper(data, amount):
np.random.seed(12345)
for i in range(data.shape[0]):
data_numpy = data[i, 0, :, :].data.cpu().numpy()
noisy_input = sp(data_numpy, amount)
data[i, 0, :, :] = torch.tensor(noisy_input).float().to('cuda')
return data
def cls_sp_validate(val_loader, model, time_begin=None):
perturbed_test_accs = []
for eps in [0, 0.02, 0.04, 0.06, 0.08, 0.1, 0.12, 0.15, 0.18, 0.2, 0.25, 0.3, 0.35]:
model.eval()
acc1_val = 0
n = 0
with torch.no_grad():
for i, (images, target) in enumerate(val_loader):
images = images.cuda(non_blocking=True)
target = target.cuda(non_blocking=True)
images = sp_wrapper(images, eps)
output = model(images)
model_logits = output[0] if (type(output) is tuple) else output
pred = model_logits.data.max(1, keepdim=True)[1] # get the index of the max log-probability
acc1_val += pred.eq(target.data.view_as(pred)).cpu().sum().item()
n += len(images)
avg_acc1 = (acc1_val / n)
perturbed_test_accs.append(avg_acc1)
print(perturbed_test_accs)
return perturbed_test_accs
if __name__ == '__main__':
parser = argparse.ArgumentParser("Noisy Feature Mixup")
parser.add_argument("--noise", default='white', type=str, help='noise type')
parser.add_argument("--data", type=str, default='cifar10', required=False, help='dataset')
parser.add_argument("--dir", type=str, default='cifar10_models/', required=False, help='model dir')
parser.add_argument("--batch_size", default=1024, type=int, help='batch size')
args = parser.parse_args()
test_batch_size = args.batch_size
if args.noise == 'white' or args.noise == 'sp' :
main(noise_type=args.noise, data=args.data, folder=args.dir, batch_size=args.batch_size)
elif args.noise =='both':
main(noise_type='white', data=args.data, folder=args.dir, batch_size=args.batch_size)
main(noise_type='sp', data=args.data, folder=args.dir, batch_size=args.batch_size)