How to use the cleverhans.model.Model function in cleverhans

To help you get started, we’ve selected a few cleverhans examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github tensorflow / cleverhans / tests_tf / test_attacks.py View on Github external
Model.__init__(self, scope, nb_classes, locals())

  def fprop(self, x, **kwargs):
    del kwargs
    with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE):
      w1 = tf.constant([[1.5, .3], [-2, 0.3]],
                       dtype=tf.as_dtype(x.dtype))
      w2 = tf.constant([[-2.4, 1.2], [0.5, -2.3]],
                       dtype=tf.as_dtype(x.dtype))
    h1 = tf.nn.sigmoid(tf.matmul(x, w1))
    res = tf.matmul(h1, w2)
    return {self.O_LOGITS: res,
            self.O_PROBS: tf.nn.softmax(res)}


class TrivialModel(Model):
  """
  A linear model with two weights
  """

  def __init__(self, scope='trivial', nb_classes=2, **kwargs):
    del kwargs
    Model.__init__(self, scope, nb_classes, locals())

  def fprop(self, x, **kwargs):
    del kwargs
    with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE):
      w1 = tf.constant([[1, -1]], dtype=tf.float32)
    res = tf.matmul(x, w1)
    return {self.O_LOGITS: res,
            self.O_PROBS: tf.nn.softmax(res)}
github tensorflow / cleverhans / tests_tf / test_attacks.py View on Github external
"""

  def __init__(self, scope='trivial', nb_classes=2, **kwargs):
    del kwargs
    Model.__init__(self, scope, nb_classes, locals())

  def fprop(self, x, **kwargs):
    del kwargs
    with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE):
      w1 = tf.constant([[1, -1]], dtype=tf.float32)
    res = tf.matmul(x, w1)
    return {self.O_LOGITS: res,
            self.O_PROBS: tf.nn.softmax(res)}


class DummyModel(Model):
  """
  A simple model based on slim
  """

  def __init__(self, scope='dummy_model', nb_classes=10, **kwargs):
    del kwargs
    Model.__init__(self, scope, nb_classes, locals())

  def fprop(self, x, **kwargs):
    del kwargs
    with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE):
      net = slim.flatten(x)
      net = slim.fully_connected(net, 60)
      logits = slim.fully_connected(net, 10, activation_fn=None)
      return {self.O_LOGITS: logits,
              self.O_PROBS: tf.nn.softmax(logits)}
github tensorflow / cleverhans / tests_tf / test_model.py View on Github external
def test_get_logits(self):
    # Define empty model
    model = Model('model', 10, {})
    x = []

    # Exception is thrown when `get_logits` not implemented
    with self.assertRaises(Exception) as context:
      model.get_logits(x)
    self.assertTrue(context.exception)
github tensorflow / cleverhans / tests_tf / test_evaluation.py View on Github external
def test_cache(self):
    """test_cache: Test that _CorrectFactory can be cached"""
    model = Model()
    factory_1 = _CorrectFactory(model)
    factory_2 = _CorrectFactory(model)
    cache = {}
    cache[factory_1] = True
    self.assertTrue(factory_2 in cache)
github tensorflow / cleverhans / examples / facenet_adversarial_faces / facenet_fgsm.py View on Github external
import facenet

import tensorflow as tf
import numpy as np
from cleverhans.model import Model
from cleverhans.attacks import FastGradientMethod

import set_loader


class InceptionResnetV1Model(Model):
  model_path = "models/facenet/20180402-114759/20180402-114759.pb"

  def __init__(self):
    super(InceptionResnetV1Model, self).__init__(scope='model')

    # Load Facenet CNN
    facenet.load_model(self.model_path)
    # Save input and output tensors references
    graph = tf.get_default_graph()
    self.face_input = graph.get_tensor_by_name("input:0")
    self.embedding_output = graph.get_tensor_by_name("embeddings:0")

  def convert_to_classifier(self):
    # Create victim_embedding placeholder
    self.victim_embedding_input = tf.placeholder(
        tf.float32,
github tensorflow / cleverhans / cleverhans / attacks / carlini_wagner_l2.py View on Github external
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.
    """
    if not isinstance(model, Model):
      wrapper_warning_logits()
      model = CallableModelWrapper(model, 'logits')

    super(CarliniWagnerL2, self).__init__(model, sess, dtypestr, **kwargs)

    self.feedable_kwargs = ('y', 'y_target')

    self.structural_kwargs = [
        'batch_size', 'confidence', 'targeted', 'learning_rate',
        'binary_search_steps', 'max_iterations', 'abort_early',
        'initial_const', 'clip_min', 'clip_max'
    ]
github poloclub / jpeg-defense / models / inception_v4.py View on Github external
import tensorflow as tf
from cleverhans.model import Model as CleverHansModel

import inception_v4_base

slim = tf.contrib.slim


class InceptionV4(CleverHansModel):
    default_image_size = inception_v4_base.default_image_size

    def __init__(self, x, checkpoint_path, num_classes=1001, is_training=False):
        super(InceptionV4, self).__init__()

        self.num_classes = num_classes
        self.checkpoint_path = checkpoint_path

        with slim.arg_scope(inception_v4_base.inception_v4_arg_scope()):
            net, end_points = inception_v4_base.inception_v4(x, num_classes=num_classes,
                                                             is_training=is_training, reuse=None)

        self.variables_to_restore = slim.get_variables_to_restore(exclude=[])
        saver = tf.train.Saver(self.variables_to_restore)
        self.load_weights = lambda sess: saver.restore(sess, checkpoint_path)
github tensorflow / cleverhans / examples / imagenet_featadvs / model.py View on Github external
def __init__(self, scope, nb_classes=1000, **kwargs):
    del kwargs
    Model.__init__(self, scope, nb_classes, locals())
github tensorflow / cleverhans / cleverhans / utils_keras.py View on Github external
Dense(nb_classes)]

  for layer in layers:
    model.add(layer)

  if logits:
    logits_tensor = model(input_ph)
  model.add(Activation('softmax'))

  if logits:
    return model, logits_tensor
  else:
    return model


class KerasModelWrapper(Model):
  """
  An implementation of `Model` that wraps a Keras model. It
  specifically exposes the hidden features of a model by creating new models.
  The symbolic graph is reused and so there is little overhead. Splitting
  in-place operations can incur an overhead.
  """

  def __init__(self, model):
    """
    Create a wrapper for a Keras model
    :param model: A Keras model
    """
    super(KerasModelWrapper, self).__init__(None, None, {})

    if model is None:
      raise ValueError('model argument must be supplied.')
github BardOfCodes / fda / fda / attacks.py View on Github external
def __init__(self, model, sess=None, dtypestr='float32',
                 default_rand_init=True, **kwargs):
        """
        Based on ProjectedGradientDescent in cleverhans.
        """
        if not isinstance(model, Model):
            model = CallableModelWrapper(model, 'probs')

        super(FDA, self).__init__(model, sess=sess,
                                  dtypestr=dtypestr, **kwargs)
        self.feedable_kwargs = {
            'eps': self.np_dtype,
            'eps_iter': self.np_dtype,
            'y': self.np_dtype,
            'y_target': self.np_dtype,
            'clip_min': self.np_dtype,
            'clip_max': self.np_dtype
        }
        self.structural_kwargs = ['ord', 'nb_iter', 'rand_init']