|
2 | 2 | """Trains a convolutional neural network on the MNIST dataset, then attacks it with the FGSM attack.""" |
3 | 3 | from __future__ import absolute_import, division, print_function, unicode_literals |
4 | 4 |
|
| 5 | +import tensorflow as tf |
| 6 | + |
| 7 | +tf.compat.v1.disable_eager_execution() |
| 8 | + |
5 | 9 | from keras.models import Sequential |
6 | 10 | from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout |
7 | 11 | import numpy as np |
|
35 | 39 | acc = np.sum(preds == np.argmax(y_test, axis=1)) / y_test.shape[0] |
36 | 40 | print("\nTest accuracy: %.2f%%" % (acc * 100)) |
37 | 41 |
|
38 | | -# Craft adversarial samples with FGSM |
39 | | -epsilon = 0.1 # Maximum perturbation |
40 | | -adv_crafter = FastGradientMethod(classifier, eps=epsilon) |
41 | | -x_test_adv = adv_crafter.generate(x=x_test) |
| 42 | +# Define epsilon values |
| 43 | +epsilon_values = [0.01, 0.1, 0.15, 0.2, 0.25, 0.3] |
42 | 44 |
|
43 | | -# Evaluate the classifier on the adversarial examples |
44 | | -preds = np.argmax(classifier.predict(x_test_adv), axis=1) |
45 | | -acc = np.sum(preds == np.argmax(y_test, axis=1)) / y_test.shape[0] |
46 | | -print("\nTest accuracy on adversarial sample: %.2f%%" % (acc * 100)) |
| 45 | +# Iterate over epsilon values |
| 46 | +for epsilon in epsilon_values: |
| 47 | + # Craft adversarial samples with FGSM |
| 48 | + adv_crafter = FastGradientMethod(classifier, eps=epsilon) |
| 49 | + x_test_adv = adv_crafter.generate(x=x_test, y=y_test) |
| 50 | + |
| 51 | + # Evaluate the classifier on the adversarial examples |
| 52 | + preds = np.argmax(classifier.predict(x_test_adv), axis=1) |
| 53 | + acc = np.sum(preds == np.argmax(y_test, axis=1)) / y_test.shape[0] |
| 54 | + print("Test accuracy on adversarial sample (epsilon = %.2f): %.2f%%" % (epsilon, acc * 100)) |
0 commit comments