-
Notifications
You must be signed in to change notification settings - Fork 8
/
run_attack.py
81 lines (60 loc) · 2.57 KB
/
run_attack.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
import tensorflow as tf
import scipy.io
import numpy as np
import argparse
from utils_pt import load_data
def load_model(dataset):
if dataset == 'mnist':
import mnist_NiN_bn
model = mnist_NiN_bn.NiN_Model()
saver = tf.train.Saver()
checkpoint = tf.train.latest_checkpoint('/home/repository_mnist_relu/Tensorflow_version/nin_model/')
saver.restore(sess, checkpoint)
elif dataset == 'cifar10':
import cifar10_NiN_bn
model = cifar10_NiN_bn.NiN_Model()
saver = tf.train.Saver()
checkpoint = tf.train.latest_checkpoint('/home/cifar-10-cnn/Tensorflow_version/nin_model/')
saver.restore(sess, checkpoint)
else:
raise ValueError('unknown dataset')
return model
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Define hyperparameters.')
parser.add_argument('--dataset', type=str, default='cifar10', help='cifar10, mnist')
parser.add_argument('--attack', type=str, default='CS', help='PGD, CS')
parser.add_argument('--path_results', type=str, default='none')
parser.add_argument('--n_examples', type=int, default=50)
parser.add_argument('--data_dir', type=str, default= './data')
hps = parser.parse_args()
sess = tf.InteractiveSession()
model = load_model(hps.dataset)
x_test, y_test = load_data(hps.dataset, hps.n_examples, hps.data_dir)
# x_test, y_test are images and labels on which the attack is run (to be loaded)
# x_test in the format bs (batch size) x heigth x width x channels
# y_test in the format bs
if hps.attack == 'PGD':
import pgd_attacks
args = {'type_attack': 'L0+sigma',
'n_restarts': 3,
'num_steps': 20,
'step_size': 120000.0/255.0/2.0,
'kappa': 0.8,
'epsilon': -1,
'sparsity': 50}
attack = pgd_attacks.PGDattack(model, args)
adv, pgd_adv_acc = attack.perturb(x_test, y_test, sess)
if hps.path_results != 'none': np.save(hps.path_results + 'results.npy', adv)
elif hps.attack == 'CS':
import cornersearch_attacks
args = {'type_attack': 'L0+sigma',
'n_iter': 1000,
'n_max': 150,
'kappa': 0.8,
'epsilon': -1,
'sparsity': 100,
'size_incr': 5}
attack = cornersearch_attacks.CSattack(model, args)
adv, pixels_changed, fl_success = attack.perturb(x_test, y_test, sess)
if hps.path_results != 'none': np.save(hps.path_results + 'results.npy', adv)
sess.close()