Skip to content

Commit 29e71d2

Browse files
authored
Merge pull request #7454 from jhtsing/develop
add bim method for generating adversarail sample
2 parents 1511a04 + 7a0f3fd commit 29e71d2

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

adversarial/advbox/attacks/gradientsign.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,39 @@ def _apply(self, image_label, epsilons=1000):
4949

5050

5151
FGSM = GradientSignAttack
52+
53+
54+
class IteratorGradientSignAttack(Attack):
55+
"""
56+
This attack was originally implemented by Alexey Kurakin(Google Brain).
57+
Paper link: https://arxiv.org/pdf/1607.02533.pdf
58+
"""
59+
60+
def _apply(self, image_label, epsilons=100, steps=10):
61+
"""
62+
Apply the iterative gradient sign attack.
63+
Args:
64+
image_label(list): The image and label tuple list of one element.
65+
epsilons(list|tuple|int): The epsilon (input variation parameter).
66+
steps(int): The number of iterator steps.
67+
Return:
68+
numpy.ndarray: The adversarail sample generated by the algorithm.
69+
"""
70+
assert len(image_label) == 1
71+
pre_label = np.argmax(self.model.predict(image_label))
72+
gradient = self.model.gradient(image_label)
73+
min_, max_ = self.model.bounds()
74+
75+
if not isinstance(epsilons, Iterable):
76+
epsilons = np.linspace(0, 1, num=epsilons + 1)
77+
78+
for epsilon in epsilons:
79+
adv_img = image_label[0][0].reshape(gradient.shape)
80+
for _ in range(steps):
81+
gradient = self.model.gradient([(adv_img, image_label[0][1])])
82+
gradient_sign = np.sign(gradient) * (max_ - min_)
83+
adv_img = adv_img + epsilon * gradient_sign
84+
adv_img = np.clip(adv_img, min_, max_)
85+
adv_label = np.argmax(self.model.predict([(adv_img, 0)]))
86+
if pre_label != adv_label:
87+
return adv_img

0 commit comments

Comments
 (0)