PEP8 test_attacks.py
@@ -6,7 +6,10 @@ from __future__ import unicode_literals
import unittest
import numpy as np
-from cleverhans.attacks import FastGradientMethod, VirtualAdversarialMethod, CarliniWagnerL2
+from cleverhans.attacks import FastGradientMethod
+from cleverhans.attacks import VirtualAdversarialMethod
+from cleverhans.attacks import CarliniWagnerL2
+
class TestVirtualAdversarialMethod(unittest.TestCase):
def setUp(self):
@@ -43,14 +46,17 @@ class TestVirtualAdversarialMethod(unittest.TestCase):
# test perturbation norm
self.assertTrue(np.allclose(perturbation_norm, self.attack.eps))
+
class TestFastGradientMethod(unittest.TestCase):
def setUp(self):
import tensorflow as tf
# The world's simplest neural network
def my_model(x):
- h1 = tf.nn.sigmoid(tf.matmul(x, tf.constant([[1.5, .3], [-2, 0.3]], dtype=tf.float32)))
- res = tf.nn.softmax(tf.matmul(x, tf.constant([[-2.4, 1.2], [0.5, -2.3]], dtype=tf.float32)))
+ W1 = tf.constant([[1.5, .3], [-2, 0.3]], dtype=tf.float32)
+ h1 = tf.nn.sigmoid(tf.matmul(x, W1))
+ W2 = tf.constant([[-2.4, 1.2], [0.5, -2.3]], dtype=tf.float32)
+ res = tf.nn.softmax(tf.matmul(x, W2))
return res
self.sess = tf.Session()
@@ -70,12 +76,12 @@ class TestFastGradientMethod(unittest.TestCase):
elif ord == 1:
assert np.allclose(np.sum(np.abs(x_adv-x_val), axis=1), 0.5)
elif ord == 2:
- assert np.allclose(np.sum(np.square(x_adv-x_val),axis=1)**.5, 0.5)
+ assert np.allclose(np.sum(np.square(x_adv-x_val), axis=1)**.5,
+ 0.5)
orig_labs = np.argmax(self.sess.run(self.model(x_val)), axis=1)
new_labs = np.argmax(self.sess.run(self.model(x_adv)), axis=1)
-
assert np.mean(orig_labs*new_labs) < 0.5
def test_generate_np_can_be_called_with_different_eps(self):
@@ -110,6 +116,7 @@ class TestFastGradientMethod(unittest.TestCase):
assert np.allclose(np.max(np.abs(x_adv-x_val), axis=1), 0.5)
old_grads = tf.gradients
+
def fn(*x, **y):
raise RuntimeError()
tf.gradients = fn
@@ -134,6 +141,7 @@ class TestFastGradientMethod(unittest.TestCase):
ok = [False]
old_grads = tf.gradients
+
def fn(*x, **y):
ok[0] = True
return old_grads(*x, **y)
@@ -149,6 +157,5 @@ class TestFastGradientMethod(unittest.TestCase):
assert ok[0]
-
if __name__ == '__main__':
unittest.main()
