forked from Jianbo-Lab/HSJA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
robust_main.py
150 lines (124 loc) · 5.56 KB
/
robust_main.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
from __future__ import absolute_import, division, print_function
from robust.build_model import ImageModel
from robust.load_data import ImageData, split_data
from hsja import hsja
import numpy as np
import sys
import os
import pickle
import argparse
import scipy
import itertools
import imageio
def construct_model_and_data(args):
"""
Load model and data on which the attack is carried out.
Assign target classes and images for targeted attack.
"""
data_model = args.method + '/' + args.dataset_name + args.model_name
dataset = ImageData(args.dataset_name)
x_test, y_test = dataset.x_val, dataset.y_val
model = ImageModel(args.model_name, args.dataset_name, args.accuracy,
train = False, load = True)
# Split the test dataset into two parts.
# Use the first part for setting target image for targeted attack.
x_train, y_train, x_test, y_test = split_data(x_test, y_test, model,
num_classes = model.num_classes, split_rate = 0.5,
sample_per_class = np.min([np.max([200, args.num_samples // 10 * 3]),
1000]))
outputs = {'data_model': data_model,
'x_test': x_test,
'y_test': y_test,
'model': model,
'clip_max': 1.0,
'clip_min': 0.0
}
#initialize random noise
random_noise = {2:'pics/robust/random_noise_2_1.npy', 6:'pics/robust/random_noise_6_1.npy'}
np.random.seed(0)
target_images = [np.random.choice([random_noise[j] for j in random_noise.keys() if j != label]) for label in y_test]
outputs['target_images'] = target_images
if args.attack_type == 'targeted':
# Assign target class and image for targeted atttack.
label_train = np.argmax(y_train, axis = 1)
label_test = np.argmax(y_test, axis = 1)
x_train_by_class = [x_train[label_train == i] for i in range(model.num_classes)]
target_img_by_class = np.array([x_train_by_class[i][0] for i in range(model.num_classes)])
np.random.seed(0)
target_labels = [np.random.choice([j for j in range(model.num_classes) if j != label]) for label in label_test]
target_img_ids = [np.random.choice(len(x_train_by_class[target_label])) for target_label in target_labels]
target_images = [x_train_by_class[target_labels[j]][target_img_id] for j, target_img_id in enumerate(target_img_ids)]
outputs['target_labels'] = target_labels
outputs['target_images'] = target_images
return outputs
def attack(args):
outputs = construct_model_and_data(args)
data_model = outputs['data_model']
x_test = outputs['x_test']
y_test = outputs['y_test']
model = outputs['model']
clip_max = outputs['clip_max']
clip_min = outputs['clip_min']
if args.attack_type == 'targeted':
target_labels = outputs['target_labels']
target_images = outputs['target_images']
for i, sample in enumerate(x_test[:args.num_samples]):
label = y_test[i]#np.argmax(y_test[i])
if args.attack_type == 'targeted':
target_label = target_labels[i]
target_image = target_images[i]
else:
target_label = None
target_image = outputs['target_images'][i]
print('attacking the {}th sample...'.format(i))
perturbed = hsja(model,
sample,
clip_max = 1,
clip_min = 0,
constraint = args.constraint,
num_iterations = args.num_iterations,
gamma = 1.0,
target_label = target_label,
target_image = target_image,
stepsize_search = args.stepsize_search,
max_num_evals = 1e4,
init_num_evals = 100)
if np.argmin(sample.shape) == 0: sample = np.transpose(sample, (1,2,0))
if np.argmin(perturbed.shape) == 0: perturbed = np.tranpose(perturbed, (1,2,0))
image = np.concatenate([sample, np.zeros((32,8,3)), perturbed], axis = 1)
imageio.imsave('{}/figs/{}-{}-{}.jpg'.format(data_model,
args.attack_type, args.constraint, i), image)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--method', type = str,
choices = ['hamming', 'euclidean', 'robust'],
default = 'hamming')
parser.add_argument('--dataset_name', type = str,
choices = ['cifar10'],
default = 'cifar10')
parser.add_argument('--model_name', type = str,
choices = ['resnet'],
default = 'resnet')
parser.add_argument('--constraint', type = str,
choices = ['l2', 'linf'],
default = 'l2')
parser.add_argument('--attack_type', type = str,
choices = ['targeted', 'untargeted'],
default = 'untargeted')
parser.add_argument('--num_samples', type = int,
default = 10)
parser.add_argument('--num_iterations', type = int,
default = 64)
parser.add_argument('--accuracy', type = float,
default = 64)
parser.add_argument('--stepsize_search', type = str,
choices = ['geometric_progression', 'grid_search'],
default = 'geometric_progression')
args = parser.parse_args()
dict_a = vars(args)
data_model = args.dataset_name + args.model_name
if not os.path.exists(data_model):
os.mkdir(data_model)
if not os.path.exists('{}/figs'.format(data_model)):
os.mkdir('{}/figs'.format(data_model))
attack(args)