def main(_):
    batch_size = FLAGS.batch_size
    batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
    with tf.Graph().as_default():
    # Prepare graph
        x_input = tf.placeholder(tf.float32, shape=batch_shape)
        
        with tf.Session() as sess:
            model = InceptionV3Model(sess=sess)
            model._build()
            mim = MIM(model, back='tf', sess=None)
            mim_params = {'eps_iter': 0.06,
                          'eps': 0.3,
                          'nb_iter': 10,
                          'ord': 2,
                          'decay_factor': 1.0}
            
            x_adv = mim.generate(x_input, **mim_params)
            j = 0
            z_samples = np.zeros((10000, 299, 299, 3))
            real_samples = np.zeros((10000, 299, 299, 3))
            for filenames, images in load_images(FLAGS.input_dir, batch_shape):
                adv_images = sess.run(x_adv, feed_dict={x_input: images})
                for (real, adv) in zip(images, adv_images):
                    z_samples[j] = adv
                    real_samples[j] = real
                    #show(real, adv, model, sess) 
                    j += 1
                if not (j % 100):
                    print j
                if j >= 5000:
                    print "Max examples exceeded, early stopping"
                    break

            save_npy(real_samples, z_samples)
def main(_):
    batch_size = FLAGS.batch_size
    batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
    num_classes = 1001
    targeted = False
    tf.logging.set_verbosity(tf.logging.DEBUG)

    with tf.Graph().as_default():
        x_input = tf.placeholder(tf.float32, shape=batch_shape)
        model = InceptionModel(num_classes)
        with tf.Session() as sess:
            predictions = model(x_input)
            mim = MIM(model, back='tf', sess=None)
            mim_params = {
                'eps_iter': 0.06,
                'eps': 0.3,
                'nb_iter': 10,
                'ord': 2,
                'decay_factor': 1.0
            }

            x_adv = mim.generate(x_input, **mim_params)
            sys.exit(0)
            saver = tf.train.Saver(slim.get_model_variables())

            saver.restore(sess, FLAGS.checkpoint_path)
            z_samples = np.zeros((10000, 299, 299, 3))
            real_samples = np.zeros((10000, 299, 299, 3))
            meta_graph_def = tf.train.export_meta_graph(
                filename='tmp/imagenet/inception_v3.meta')
            saver.save(sess, 'tmp/imagenet/inception_v3.ckpt')
            #freeze_graph(sess)
            sys.exit(0)
            """
            a = [n.name for n in tf.get_default_graph().as_graph_def().node]
            for item in a:
                print item
            """
            j = 0
            for filenames, images in load_images(FLAGS.input_dir, batch_shape):
                adv_images = sess.run(x_adv, feed_dict={x_input: images})
                for (real, adv) in zip(images, adv_images):
                    z_samples[j] = adv
                    real_samples[j] = real
                    j += 1
                if not (j % 100):
                    print j
                if j >= 5000:
                    print "Max examples exceeded, early stopping"
                    break

            save_npy(real_samples, z_samples)
Пример #3
0
def main(_):
    # Images for inception classifier are normalized to be in [-1, 1] interval,
    # eps is a difference between pixels so it should be in [0, 2] interval.
    # Renormalizing epsilon from [0, 255] to [0, 2].
    batch_size = FLAGS.batch_size
    batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
    num_classes = 1001
    targeted = False
    tf.logging.set_verbosity(tf.logging.DEBUG)

    with tf.Graph().as_default():
        # Prepare graph
        x_input = tf.placeholder(tf.float32, shape=batch_shape)
        model = InceptionModel(num_classes)
        with tf.Session() as sess:

            mim = MIM(model, back='tf', sess=None)
            mim_params = {
                'eps_iter': 0.06,
                'eps': 0.3,
                'nb_iter': 10,
                'ord': 2,
                'decay_factor': 1.0
            }

            x_adv = mim.generate(x_input, **mim_params)

            saver = tf.train.Saver(slim.get_model_variables())
            session_creator = tf.train.ChiefSessionCreator(
                scaffold=tf.train.Scaffold(saver=saver),
                checkpoint_filename_with_path=FLAGS.checkpoint_path,
                master=FLAGS.master)
            saver.restore(sess, FLAGS.checkpoint_path)
            sess.run(tf.global_variables_initializer())
            # with tf.train.MonitoredSession(session_creator=session_creator) as sess:
            i = 0
            for filenames, images in load_images(FLAGS.input_dir, batch_shape):
                adv_images = sess.run(x_adv, feed_dict={x_input: images})
                print "input images: ", images.shape
                #adv_images = cw.generate_np(images, **cw_params)
                i += 16
                print i
                # print filenames
                # print adv_images.shape
                # adv_images = cw.generate_np(
                save_images(adv_images, filenames, FLAGS.output_dir)
Пример #4
0
def main(_):
    # Images for inception classifier are normalized to be in [-1, 1] interval,
    # eps is a difference between pixels so it should be in [0, 2] interval.
    # Renormalizing epsilon from [0, 255] to [0, 2].
    eps = 2.0 * FLAGS.max_epsilon / 255.0
    batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
    num_classes = 1001

    tf.logging.set_verbosity(tf.logging.INFO)

    with tf.Graph().as_default():
        # Prepare graph
        x_input = tf.placeholder(tf.float32, shape=batch_shape)
        model = InceptionModel(num_classes)

        mim = MIM(model, back='tf', sess=None)
        mim_params = {
            'eps_iter': 0.06,
            'eps': 0.3,
            'nb_iter': 10,
            'ord': 2,
            'decay_factor': 1.0
        }

        x_adv = mim.generate(x_input, **mim_params)

        # Run computation
        saver = tf.train.Saver(slim.get_model_variables())
        session_creator = tf.train.ChiefSessionCreator(
            scaffold=tf.train.Scaffold(saver=saver),
            checkpoint_filename_with_path=FLAGS.checkpoint_path,
            master=FLAGS.master)

        with tf.train.MonitoredSession(
                session_creator=session_creator) as sess:
            for filenames, images in load_images(FLAGS.input_dir, batch_shape):
                adv_images = sess.run(x_adv, feed_dict={x_input: images})
                save_images(adv_images, filenames, FLAGS.output_dir)
def main(argv=None):
    """
    CIFAR10 CleverHans tutorial
    :return:
    """

    # Set TF random seed to improve reproducibility
    tf.set_random_seed(1234)

    if not hasattr(backend, "tf"):
        raise RuntimeError("This tutorial requires keras to be configured"
                           " to use the TensorFlow backend.")

    if keras.backend.image_dim_ordering() != 'tf':
        keras.backend.set_image_dim_ordering('tf')

    # Create TF session and set as Keras backend session
    sess = tf.Session()
    keras.backend.set_session(sess)

    # Get CIFAR10 test data
    X_train, Y_train, X_test, Y_test = data_cifar10()

    assert Y_train.shape[1] == 10.
    label_smooth = .1
    Y_train = Y_train.clip(label_smooth / 9., 1. - label_smooth)

    # Define input TF placeholder
    x = tf.placeholder(tf.float32, shape=(None, 32, 32, 3))
    y = tf.placeholder(tf.float32, shape=(None, 10))

    # Define TF model graph
    model = cnn_model(img_rows=32, img_cols=32, channels=3)
    predictions = model(x)
    print "Defined TensorFlow model graph."

    def evaluate():
        # Evaluate the accuracy of the CIFAR10 model on legitimate test
        # examples
        eval_params = {'batch_size': FLAGS.batch_size}
        accuracy = model_eval(sess,
                              x,
                              y,
                              predictions,
                              X_test,
                              Y_test,
                              args=eval_params)
        assert X_test.shape[0] == 10000, X_test.shape
        print 'Test accuracy on legitimate test examples: ' + str(accuracy)

    # Train an CIFAR10 model
    train_params = {
        'nb_epochs': FLAGS.nb_epochs,
        'batch_size': FLAGS.batch_size,
        'learning_rate': FLAGS.learning_rate
    }
    model_train(sess,
                x,
                y,
                predictions,
                X_train,
                Y_train,
                evaluate=evaluate,
                args=train_params)

    # Craft adversarial examples using Fast Gradient Sign Method (FGSM)
    # adv_x = fgsm(x, predictions, eps=0.3)

    mim = MIM(model, back='tf', sess=sess)
    mim_params = {
        'eps_iter': 0.06,
        'eps': 0.3,
        'nb_iter': 10,
        'ord': 2,
        'decay_factor': 1.0
    }

    adv_x = mim.generate(x, **mim_params)

    eval_params = {'batch_size': FLAGS.batch_size}
    X_test_adv, = batch_eval(sess, [x], [adv_x], [X_test], args=eval_params)
    assert X_test_adv.shape[0] == 10000, X_test_adv.shape
    accuracy = model_eval(sess,
                          x,
                          y,
                          predictions,
                          X_test_adv,
                          Y_test,
                          args=eval_params)
    print 'Test accuracy on adversarial examples: ' + str(accuracy)

    from scipy.misc import imsave
    path = '/home/neale/repos/adversarial-toolbox/images/adversarials/mim/cifar/symmetric/'
    """
    for i, (real, adv) in enumerate(zip(X_test, X_test_adv)):
        imsave(path+'adv/adv_{}.png'.format(i), adv)
    """
    preds = model_argmax(sess, x, predictions, X_test_adv)
    print Y_test.shape
    print preds.shape
    count = 0
    for i in range(len(preds)):
        if np.argmax(Y_test[i]) == preds[i]:
            # imsave(path+'real/im_{}.png'.format(i), X_test[i])
            # imsave(path+'adv/adv_{}.png'.format(i), X_test_adv[i])
            count += 1
    print "saved ", count