forked from Trusted-AI/adversarial-robustness-toolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_started_inverse_gan.py
158 lines (115 loc) · 5.33 KB
/
get_started_inverse_gan.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
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import numpy as np
import tensorflow as tf
from art.estimators.classification import TensorFlowClassifier
from art.defences.preprocessor.inverse_gan import InverseGAN
from art.estimators.encoding.tensorflow import TensorFlowEncoder
from art.estimators.generation.tensorflow import TensorFlowGenerator
from art.utils import load_mnist
from art.attacks.evasion import FastGradientMethod
from examples.inverse_gan_author_utils import EncoderReconstructor, GeneratorReconstructor
logging.root.setLevel(logging.NOTSET)
logging.basicConfig(level=logging.NOTSET)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
def create_ts1_art_mnist_classifier(min_pixel_value, max_pixel_value):
input_ph = tf.placeholder(tf.float32, shape=[None, 28, 28, 1])
labels_ph = tf.placeholder(tf.int32, shape=[None, 10])
x = tf.layers.conv2d(input_ph, filters=4, kernel_size=5, activation=tf.nn.relu)
x = tf.layers.max_pooling2d(x, 2, 2)
x = tf.layers.conv2d(x, filters=10, kernel_size=5, activation=tf.nn.relu)
x = tf.layers.max_pooling2d(x, 2, 2)
x = tf.contrib.layers.flatten(x)
x = tf.layers.dense(x, 100, activation=tf.nn.relu)
logits = tf.layers.dense(x, 10)
loss = tf.reduce_mean(tf.losses.softmax_cross_entropy(logits=logits, onehot_labels=labels_ph))
optimizer = tf.train.AdamOptimizer(learning_rate=0.01)
train = optimizer.minimize(loss)
sess.run(tf.global_variables_initializer())
classifier = TensorFlowClassifier(
clip_values=(min_pixel_value, max_pixel_value),
input_ph=input_ph,
output=logits,
labels_ph=labels_ph,
train=train,
loss=loss,
learning=None,
sess=sess,
preprocessing_defences=[],
)
return classifier
def create_ts1_encoder_model(batch_size):
encoder_reconstructor = EncoderReconstructor(batch_size)
unmodified_z_tensor, images_tensor = encoder_reconstructor.generate_z_extrapolated_k()
encoder = TensorFlowEncoder(
input_ph=images_tensor,
model=unmodified_z_tensor,
sess=sess,
)
return encoder
def create_ts1_generator_model(batch_size):
generator = GeneratorReconstructor(batch_size)
generator.sess.run(generator.init_opt)
generator = TensorFlowGenerator(
input_ph=generator.z_general_placeholder,
model=generator.z_hats_recs,
sess=generator.sess,
)
return generator
def get_accuracy(y_pred, y):
accuracy = np.sum(np.argmax(y_pred, axis=1) == np.argmax(y, axis=1)) / len(y)
return round(accuracy * 100, 2)
def main():
# SETTING UP DEFENCE GAN TRAINED MODELS
# * Clone the defence gan gitrepo https://github.com/yogeshbalaji/InvGAN
# * Follow the setup instructions and copy the following:
# * data/ to adversarial-robustness-toolbox/defence_gan/data/
# * output/gans/mnist to adversarial-robustness-toolbox/defence_gan/output/gans/mnist
# * output/gans_inv_nottrain/mnist to adversarial-robustness-toolbox/defence_gan/output/gans_inv_nottrain/mnist
# STEP 0
logging.info("Loading a Dataset")
(_, _), (x_test_original, y_test_original), min_pixel_value, max_pixel_value = load_mnist()
# TODO remove before PR request
# batch_size = x_test_original.shape[0]
batch_size = 1000
(x_test, y_test) = (x_test_original[:batch_size], y_test_original[:batch_size])
# STEP 1
logging.info("Creating a TS1 Mnist Classifier")
classifier = create_ts1_art_mnist_classifier(min_pixel_value, max_pixel_value)
classifier.fit(x_test, y_test, batch_size=batch_size, nb_epochs=3)
# Code to load the original defense_gan paper mnist classifier to reproduce paper results
# classifier_paper = create_defense_gan_paper_mnist_art_classifier()
# STEP 2
logging.info("Evaluate the ART classifier on non adversarial examples")
predictions = classifier.predict(x_test)
accuracy_non_adv = get_accuracy(predictions, y_test)
# STEP 3
logging.info("Generate adversarial examples")
attack = FastGradientMethod(classifier, eps=0.2)
x_test_adv = attack.generate(x=x_test)
# STEP 4
logging.info("Evaluate the classifier on the adversarial examples")
predictions = classifier.predict(x_test_adv)
accuracy_adv = get_accuracy(predictions, y_test)
# STEP 5
logging.info("Create DefenceGAN")
encoder = create_ts1_encoder_model(batch_size)
generator = create_ts1_generator_model(batch_size)
inverse_gan = InverseGAN(sess=generator._sess, gan=generator, inverse_gan=encoder)
# defense_gan = DefenseGAN(sess=generator.sess,
# generator=generator)
logging.info("Generating Defended Samples")
x_test_defended = inverse_gan(x_test_adv, maxiter=1)
# STEP 6
logging.info("Evaluate the classifier on the defended examples")
predictions = classifier.predict(x_test_defended)
accuracy_defended = get_accuracy(predictions, y_test)
logger.info("Accuracy on non adversarial examples: {}%".format(accuracy_non_adv))
logger.info("Accuracy on adversarial examples: {}%".format(accuracy_adv))
logger.info("Accuracy on defended examples: {}%".format(accuracy_defended))
if __name__ == "__main__":
main()