def generate(self, inputs, labels):
        """
        Generate adversarial examples based on input data and origin/target labels.

        Args:
            inputs (Union[numpy.ndarray, tuple]): Benign input samples used as references to
                create adversarial examples.
            labels (Union[numpy.ndarray, tuple]): Original/target labels. \
                For each input if it has more than one label, it is wrapped in a tuple.

        Returns:
            numpy.ndarray, generated adversarial examples.

        Examples:
            >>> adv_x = attack.generate([[0.5, 0.2, 0.6],
            >>>                          [0.3, 0, 0.2]],
            >>>                         [[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            >>>                          [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]])
        """
        inputs_image, inputs, labels = check_inputs_labels(inputs, labels)
        arr_x = inputs_image
        momentum = 0
        if self._bounds is not None:
            clip_min, clip_max = self._bounds
            clip_diff = clip_max - clip_min
            for _ in range(self._nb_iter):
                if 'self._prob' in globals():
                    d_inputs = _transform_inputs(inputs_image, self._prob)
                else:
                    d_inputs = inputs_image
                if isinstance(inputs, tuple):
                    d_inputs = (d_inputs,) + inputs[1:]
                gradient = self._gradient(d_inputs, labels)
                momentum = self._decay_factor*momentum + gradient
                if isinstance(d_inputs, tuple):
                    adv_x = d_inputs[0] + self._eps_iter*np.sign(momentum)
                else:
                    adv_x = d_inputs + self._eps_iter*np.sign(momentum)
                perturs = np.clip(adv_x - arr_x, (0 - self._eps)*clip_diff,
                                  self._eps*clip_diff)
                adv_x = arr_x + perturs
                adv_x = np.clip(adv_x, clip_min, clip_max)
                inputs_image = adv_x
        else:
            for _ in range(self._nb_iter):
                if 'self._prob' in globals():
                    d_inputs = _transform_inputs(inputs_image, self._prob)
                else:
                    d_inputs = inputs_image
                if isinstance(inputs, tuple):
                    d_inputs = (d_inputs,) + inputs[1:]
                gradient = self._gradient(d_inputs, labels)
                momentum = self._decay_factor*momentum + gradient
                if isinstance(d_inputs, tuple):
                    adv_x = d_inputs[0] + self._eps_iter*np.sign(momentum)
                else:
                    adv_x = d_inputs + self._eps_iter*np.sign(momentum)
                adv_x = np.clip(adv_x, arr_x - self._eps, arr_x + self._eps)
                inputs_image = adv_x
        return adv_x
Пример #2
0
    def generate(self, inputs, labels):
        """
        Generate adversarial examples based on input samples and original/target labels.

        Args:
            inputs (Union[numpy.ndarray, tuple]): Benign input samples used as references to create
                    adversarial examples.
            labels (Union[numpy.ndarray, tuple]): Original/target labels. \
                For each input if it has more than one label, it is wrapped in a tuple.

        Returns:
            numpy.ndarray, generated adversarial examples.
        """
        inputs_image, inputs, labels = check_inputs_labels(inputs, labels)
        self._dtype = inputs_image.dtype
        gradient = self._gradient(inputs, labels)
        # use random method or not
        if self._alpha is not None:
            random_part = self._alpha * np.sign(
                np.random.normal(size=inputs.shape)).astype(self._dtype)
            perturbation = (self._eps - self._alpha) * gradient + random_part
        else:
            perturbation = self._eps * gradient

        if self._bounds is not None:
            clip_min, clip_max = self._bounds
            perturbation = perturbation * (clip_max - clip_min)
            adv_x = inputs_image + perturbation
            adv_x = np.clip(adv_x, clip_min, clip_max)
        else:
            adv_x = inputs_image + perturbation
        return adv_x
    def generate(self, inputs, labels):
        """
        Iteratively generate adversarial examples based on BIM method. The
        perturbation is normalized by projected method with parameter norm_level .

        Args:
            inputs (Union[numpy.ndarray, tuple]): Benign input samples used as references to
                create adversarial examples.
            labels (Union[numpy.ndarray, tuple]): Original/target labels. \
                For each input if it has more than one label, it is wrapped in a tuple.

        Returns:
            numpy.ndarray, generated adversarial examples.

        Examples:
            >>> adv_x = attack.generate([[0.6, 0.2, 0.6],
            >>>                          [0.3, 0.3, 0.4]],
            >>>                         [[0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            >>>                          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
        """
        inputs_image, inputs, labels = check_inputs_labels(inputs, labels)
        arr_x = inputs_image
        if self._bounds is not None:
            clip_min, clip_max = self._bounds
            clip_diff = clip_max - clip_min
            for _ in range(self._nb_iter):
                adv_x = self._attack.generate(inputs, labels)
                perturs = _projection(adv_x - arr_x,
                                      self._eps,
                                      norm_level=self._norm_level)
                perturs = np.clip(perturs, (0 - self._eps)*clip_diff,
                                  self._eps*clip_diff)
                adv_x = arr_x + perturs
                if isinstance(inputs, tuple):
                    inputs = (adv_x,) + inputs[1:]
                else:
                    inputs = adv_x
        else:
            for _ in range(self._nb_iter):
                adv_x = self._attack.generate(inputs, labels)
                perturs = _projection(adv_x - arr_x,
                                      self._eps,
                                      norm_level=self._norm_level)
                adv_x = arr_x + perturs
                adv_x = np.clip(adv_x, arr_x - self._eps, arr_x + self._eps)
                if isinstance(inputs, tuple):
                    inputs = (adv_x,) + inputs[1:]
                else:
                    inputs = adv_x
        return adv_x
    def generate(self, inputs, labels):

        """
        Simple iterative FGSM method to generate adversarial examples.

        Args:
            inputs (Union[numpy.ndarray, tuple]): Benign input samples used as references to
                create adversarial examples.
            labels (Union[numpy.ndarray, tuple]): Original/target labels. \
                For each input if it has more than one label, it is wrapped in a tuple.
        Returns:
            numpy.ndarray, generated adversarial examples.

        Examples:
            >>> adv_x = attack.generate([[0.3, 0.2, 0.6],
            >>>                          [0.3, 0.2, 0.4]],
            >>>                         [[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
            >>>                          [0, 0, 0, 0, 0, 0, 1, 0, 0, 0]])
        """
        inputs_image, inputs, labels = check_inputs_labels(inputs, labels)
        arr_x = inputs_image
        if self._bounds is not None:
            clip_min, clip_max = self._bounds
            clip_diff = clip_max - clip_min
            for _ in range(self._nb_iter):
                if 'self._prob' in globals():
                    d_inputs = _transform_inputs(inputs_image, self._prob)
                else:
                    d_inputs = inputs_image
                if isinstance(inputs, tuple):
                    d_inputs = (d_inputs,) + inputs[1:]
                adv_x = self._attack.generate(d_inputs, labels)
                perturs = np.clip(adv_x - arr_x, (0 - self._eps)*clip_diff,
                                  self._eps*clip_diff)
                adv_x = arr_x + perturs
                inputs_image = adv_x
        else:
            for _ in range(self._nb_iter):
                if 'self._prob' in globals():
                    d_inputs = _transform_inputs(inputs_image, self._prob)
                else:
                    d_inputs = inputs_image
                if isinstance(inputs, tuple):
                    d_inputs = (inputs_image,) + inputs[1:]
                adv_x = self._attack.generate(d_inputs, labels)
                adv_x = np.clip(adv_x, arr_x - self._eps, arr_x + self._eps)
                inputs_image = adv_x
        return adv_x
Пример #5
0
    def batch_generate(self, inputs, labels, batch_size=64):
        """
        Generate adversarial examples in batch, based on input samples and
        their labels.

        Args:
            inputs (Union[numpy.ndarray, tuple]): Samples based on which adversarial
                examples are generated.
            labels (Union[numpy.ndarray, tuple]): Original/target labels. \
                For each input if it has more than one label, it is wrapped in a tuple.
            batch_size (int): The number of samples in one batch. Default: 64.

        Returns:
            numpy.ndarray, generated adversarial examples

        Examples:
            >>> inputs = np.array([[0.2, 0.4, 0.5, 0.2], [0.7, 0.2, 0.4, 0.3]])
            >>> labels = np.array([3, 0])
            >>> advs = attack.batch_generate(inputs, labels, batch_size=2)
        """
        inputs_image, inputs, labels = check_inputs_labels(inputs, labels)
        arr_x = inputs
        arr_y = labels
        len_x = inputs_image.shape[0]
        batch_size = check_int_positive('batch_size', batch_size)
        batches = int(len_x / batch_size)
        rest = len_x - batches * batch_size
        res = []
        for i in range(batches):
            if isinstance(arr_x, tuple):
                x_batch = tuple([
                    sub_items[i * batch_size:(i + 1) * batch_size]
                    for sub_items in arr_x
                ])
            else:
                x_batch = arr_x[i * batch_size:(i + 1) * batch_size]
            if isinstance(arr_y, tuple):
                y_batch = tuple([
                    sub_labels[i * batch_size:(i + 1) * batch_size]
                    for sub_labels in arr_y
                ])
            else:
                y_batch = arr_y[i * batch_size:(i + 1) * batch_size]
            adv_x = self.generate(x_batch, y_batch)
            # Black-attack methods will return 3 values, just get the second.
            res.append(adv_x[1] if isinstance(adv_x, tuple) else adv_x)

        if rest != 0:
            if isinstance(arr_x, tuple):
                x_batch = tuple(
                    [sub_items[batches * batch_size:] for sub_items in arr_x])
            else:
                x_batch = arr_x[batches * batch_size:]
            if isinstance(arr_y, tuple):
                y_batch = tuple([
                    sub_labels[batches * batch_size:] for sub_labels in arr_y
                ])
            else:
                y_batch = arr_y[batches * batch_size:]
            adv_x = self.generate(x_batch, y_batch)
            # Black-attack methods will return 3 values, just get the second.
            res.append(adv_x[1] if isinstance(adv_x, tuple) else adv_x)

        adv_x = np.concatenate(res, axis=0)
        return adv_x