attack_params = self.attack_params
        if attack_params is None:
            attack_params = {}
        if self.pass_y:
            x_adv = self.attack.generate(x_batch, y=y_batch, **attack_params)
        else:
            # Some code checks the keys of kwargs, rather than checking if
            # y is None, so we need to truly not pass y at all, rather than
            # just passing a None value for it.
            x_adv = self.attack.generate(x_batch, **attack_params)

        return (x_batch, y_batch), tuple([x_adv])


_logger = create_logger("cleverhans.evaluation")

# Cache for storing output of `batch_eval_multi_worker`'s calls to
# `graph_factory`, to avoid making the tf graph too big
_batch_eval_multi_worker_cache = {}


def _check_x(x):
    """
  Makes sure an `x` argument is a valid numpy dataset.
  """
    if not isinstance(x, np.ndarray):
        raise TypeError("x must be a numpy array. Typically x contains "
                        "the entire test set inputs.")

Esempio n. 2
0
"""The LBFGS attack
"""

import numpy as np
import tensorflow as tf

from cleverhansl2l.attacks.attack import Attack
from cleverhansl2l.compat import reduce_sum, softmax_cross_entropy_with_logits
from cleverhansl2l.model import CallableModelWrapper, Model, wrapper_warning
from cleverhansl2l import utils
from cleverhansl2l import utils_tf

_logger = utils.create_logger("cleverhans.attacks.lbfgs")
tf_dtype = tf.as_dtype('float32')

class LBFGS(Attack):
  """
  LBFGS is the first adversarial attack for convolutional neural networks,
  and is a target & iterative attack.
  Paper link: "https://arxiv.org/pdf/1312.6199.pdf"

  :param model: cleverhans.model.Model
  :param sess: tf.Session
  :param dtypestr: dtype of the data
  :param kwargs: passed through to super constructor
  """

  def __init__(self, model, sess, dtypestr='float32', **kwargs):
    """
    Note: the model parameter should be an instance of the
    cleverhans.model.Model abstraction provided by CleverHans.
Esempio n. 3
0
import os
import time
import warnings

import math
import numpy as np
from six.moves import xrange
import tensorflow as tf

from cleverhansl2l import canary
from cleverhansl2l.utils import _ArgsWrapper, create_logger
from cleverhansl2l.utils import safe_zip
from cleverhansl2l.utils_tf import infer_devices
from cleverhansl2l.utils_tf import initialize_uninitialized_global_variables

_logger = create_logger("train")
_logger.setLevel(logging.INFO)


def train(sess,
          loss,
          x_train,
          y_train,
          init_all=False,
          evaluate=None,
          feed=None,
          args=None,
          rng=None,
          var_list=None,
          fprop_args=None,
          optimizer=None,
Esempio n. 4
0
import os
import time
import warnings

import numpy as np
import six
from six.moves import xrange
import tensorflow as tf

from cleverhansl2l.compat import device_lib
from cleverhansl2l.compat import reduce_sum, reduce_mean
from cleverhansl2l.compat import reduce_max
from cleverhansl2l.compat import softmax_cross_entropy_with_logits
from cleverhansl2l.utils import batch_indices, _ArgsWrapper, create_logger

_logger = create_logger("cleverhans.utils.tf")
_logger.setLevel(logging.INFO)


def model_loss(y, model, mean=True):
  """
  Define loss of TF graph
  :param y: correct labels
  :param model: output of the model
  :param mean: boolean indicating whether should return mean of loss
               or vector of losses for each input of the batch
  :return: return mean of loss if True, otherwise return vector with per
           sample loss
  """
  warnings.warn("This function is deprecated and will be removed on or after"
                " 2019-04-05. Switch to cleverhans.train.train.")
"""
Attacks for TensorFlow Eager
"""
from distutils.version import LooseVersion

import numpy as np
import tensorflow as tf

from cleverhansl2l import attacks
from cleverhansl2l import utils
from cleverhansl2l.model import CallableModelWrapper, wrapper_warning
from cleverhansl2l.model import Model
from cleverhansl2l.loss import LossCrossEntropy

_logger = utils.create_logger("cleverhans.attacks_tfe")

if LooseVersion(tf.__version__) < LooseVersion('1.8.0'):
    error_msg = ('For eager execution',
                 'use Tensorflow version greather than 1.8.0.')
    raise ValueError(error_msg)


class Attack(attacks.Attack):
    """
  Abstract base class for all eager attack classes.
  :param model: An instance of the cleverhans.model.Model class.
  :param back: The backend to use. Inherited from AttackBase class.
  :param dtypestr: datatype of the input data samples and crafted
                   adversarial attacks.
  """
    def __init__(self, model, dtypestr='float32'):