From fb30b3fcb00e9b0ac6e120c5542fbe1af1d70a14 Mon Sep 17 00:00:00 2001 From: guangzhuwu Date: Thu, 25 Jan 2018 17:10:03 +0800 Subject: [PATCH] Fix shape bug. --- fluid/adversarial/advbox/adversary.py | 3 ++- fluid/adversarial/advbox/attacks/gradientsign.py | 4 +++- fluid/adversarial/advbox/attacks/iterator_gradientsign.py | 4 +++- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/fluid/adversarial/advbox/adversary.py b/fluid/adversarial/advbox/adversary.py index ae0fd127..0f856332 100644 --- a/fluid/adversarial/advbox/adversary.py +++ b/fluid/adversarial/advbox/adversary.py @@ -90,7 +90,8 @@ class Adversary(object): assert adversarial_example.shape == self.__original.shape ok = self._is_successful(adversarial_label) if ok: - self.__adversarial_example = adversarial_example + self.__adversarial_example = adversarial_example.reshape( + self.__original.shape) self.__adversarial_label = adversarial_label return ok diff --git a/fluid/adversarial/advbox/attacks/gradientsign.py b/fluid/adversarial/advbox/attacks/gradientsign.py index 6c56b0d5..eccece6b 100644 --- a/fluid/adversarial/advbox/attacks/gradientsign.py +++ b/fluid/adversarial/advbox/attacks/gradientsign.py @@ -44,8 +44,10 @@ class GradientSignAttack(Attack): gradient = self.model.gradient([(adversary.original, adversary.original_label)]) gradient_sign = np.sign(gradient) * (max_ - min_) + + adv_img = adversary.original.reshape(gradient_sign.shape) for epsilon in epsilons: - adv_img = adversary.original + epsilon * gradient_sign + adv_img = adv_img + epsilon * gradient_sign adv_img = np.clip(adv_img, min_, max_) adv_label = np.argmax(self.model.predict([(adv_img, 0)])) logging.info('epsilon = {:.3f}, pre_label = {}, adv_label={}'. diff --git a/fluid/adversarial/advbox/attacks/iterator_gradientsign.py b/fluid/adversarial/advbox/attacks/iterator_gradientsign.py index 14f97c60..c0ff2362 100644 --- a/fluid/adversarial/advbox/attacks/iterator_gradientsign.py +++ b/fluid/adversarial/advbox/attacks/iterator_gradientsign.py @@ -35,7 +35,7 @@ class IteratorGradientSignAttack(Attack): min_, max_ = self.model.bounds() for epsilon in epsilons: - adv_img = adversary.original + adv_img = None for _ in range(steps): if adversary.is_targeted_attack: gradient = self.model.gradient([(adversary.original, @@ -45,6 +45,8 @@ class IteratorGradientSignAttack(Attack): gradient = self.model.gradient([(adversary.original, adversary.original_label)]) gradient_sign = np.sign(gradient) * (max_ - min_) + if adv_img is None: + adv_img = adversary.original.reshape(gradient_sign.shape) adv_img = adv_img + gradient_sign * epsilon adv_img = np.clip(adv_img, min_, max_) adv_label = np.argmax(self.model.predict([(adv_img, 0)])) -- GitLab