查看原文
其他

教程 | 经得住考验的「假图片」:用TensorFlow为神经网络生成对抗样本

2017-08-12 机器之心

选自arXiv

作者:Anish Athalye

机器之心编译

参与:李泽南


用于识别图片中物体的神经网络可以被精心设计的对抗样本欺骗,而这些在人类看起来没有什么问题的图片是如何产生的呢?最近,来自 OpenAI 的研究者 Anish Athalye 等人撰文介绍了他们使用 TensorFlow 制作「假图片」的方法。


为神经网络加入对抗样本是一个简单而有意义的工作:仔细设计的「扰动」输入可以让神经网络受到分类任务上的挑战。这些对抗样本如果应用到现实世界中可能会导致安全问题,因此非常值得关注。



仅仅加入一些特殊的噪点,图像识别系统就会把大熊猫认作是长臂猿——而且是 99% 置信度。想象一下,如果无人驾驶汽车遇到了这种情况……


在本文中,我们将简要介绍用于合成对抗样本的算法,并将演示如何将其应用到 TensorFlow 中,构建稳固对抗样本的方法。


Jupyter notebook 可执行文件:http://www.anishathalye.com/media/2017/07/25/adversarial.ipynb


设置


我们选择攻击用 ImageNet 训练的 Inception v3 模型。在这一节里,我们会从 TF-slim 图像分类库中加载一个预训练的神经网络。

  1. import tensorflow as tf

  2. import tensorflow.contrib.slim as slim

  3. import tensorflow.contrib.slim.nets as nets



  1. tf.logging.set_verbosity(tf.logging.ERROR)

  2. sess = tf.InteractiveSession()


首先,我们需要设置一张输入图片。我们使用 tf.Variable 而非 tf.placeholder 是因为我们会需要让数据可被训练,这样我们就可以在需要时继续输入。


  1. image = tf.Variable(tf.zeros((299, 299, 3)))


随后,我们加载 Inception v3 模型。


  1. def inception(image, reuse):

  2.    preprocessed = tf.multiply(tf.subtract(tf.expand_dims(image, 0), 0.5), 2.0)

  3.    arg_scope = nets.inception.inception_v3_arg_scope(weight_decay=0.0)

  4.    with slim.arg_scope(arg_scope):

  5.        logits, _ = nets.inception.inception_v3(

  6.            preprocessed, 1001, is_training=False, reuse=reuse)

  7.        logits = logits[:,1:] # ignore background class

  8.        probs = tf.nn.softmax(logits) # probabilities

  9.    return logits, probs

  10. logits, probs = inception(image, reuse=False)



接下来,我们加载预训练权重。这种 Inception v3 模型的 top-5 正确率为 93.9%。


  1. import tempfile

  2. from urllib.request import urlretrieve

  3. import tarfile

  4. import os


  1. data_dir = tempfile.mkdtemp()

  2. inception_tarball, _ = urlretrieve(

  3.    'http://download.tensorflow.org/models/inception_v3_2016_08_28.tar.gz')

  4. tarfile.open(inception_tarball, 'r:gz').extractall(data_dir)


  1. restore_vars = [

  2.    var for var in tf.global_variables()

  3.    if var.name.startswith('InceptionV3/')

  4. ]

  5. saver = tf.train.Saver(restore_vars)

  6. saver.restore(sess, os.path.join(data_dir, 'inception_v3.ckpt'))


接下来,我们编写代码来显示一张图片,对其进行分类,并显示分类结果。


  1. import json

  2. import matplotlib.pyplot as plt



  1. imagenet_json, _ = urlretrieve(

  2.    'http://www.anishathalye.com/media/2017/07/25/imagenet.json')

  3. with open(imagenet_json) as f:

  4.    imagenet_labels = json.load(f)


  1. def classify(img, correct_class=None, target_class=None):

  2.    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 8))

  3.    fig.sca(ax1)

  4.    p = sess.run(probs, feed_dict={image: img})[0]

  5.    ax1.imshow(img)

  6.    fig.sca(ax1)

  7.    topk = list(p.argsort()[-10:][::-1])

  8.    topprobs = p[topk]

  9.    barlist = ax2.bar(range(10), topprobs)

  10.    if target_class in topk:

  11.        barlist[topk.index(target_class)].set_color('r')

  12.    if correct_class in topk:

  13.        barlist[topk.index(correct_class)].set_color('g')

  14.    plt.sca(ax2)

  15.    plt.ylim([0, 1.1])

  16.    plt.xticks(range(10),

  17.               [imagenet_labels[i][:15] for i in topk],

  18.               rotation='vertical')

  19.    fig.subplots_adjust(bottom=0.2)

  20.    plt.show()


示例图片


我们加载示例图片,并确认它们已被正确分类。


  1. import PIL

  2. import numpy as np


  1. img_path, _ = urlretrieve('http://www.anishathalye.com/media/2017/07/25/cat.jpg')

  2. img_class = 281

  3. img = PIL.Image.open(img_path)

  4. big_dim = max(img.width, img.height)

  5. wide = img.width > img.height

  6. new_w = 299 if not wide else int(img.width * 299 / img.height)

  7. new_h = 299 if wide else int(img.height * 299 / img.width)

  8. img = img.resize((new_w, new_h)).crop((0, 0, 299, 299))

  9. img = (np.asarray(img) / 255.0).astype(np.float32)


  1. classify(img, correct_class=img_class)




对抗样本


给定图片 X,我们的神经网络输出 P(y|x)上的概率分布。当我们制作对抗性输入时,我们想找到一个 x ^,其中 logP(y ^ | x ^)对于目标标签 y ^是最大化的:这样,我们的输入就会被误分类为目标类别中。我们可以通过把自己约束在半径为ϵ的ℓ∞框中来确保 x ^看起来与原始的 x 看起来差不多,这就需要∥x−x^∥∞≤ϵ了。


在这个框架中,一个对抗性样本是约束优化问题的解,我们可以使用反向传播和预测梯度下降来求得它,这基本上是用于训练网络本身的相同技术。算法很简单:


我们首先将对抗样本初始化为 x^←x。然后重复以下过程直到收敛为止:




初始化


我们先从最简单的开始:写一个用于初始化的 TensorFlow op。


  1. x = tf.placeholder(tf.float32, (299, 299, 3))

  2. x_hat = image # our trainable adversarial input

  3. assign_op = tf.assign(x_hat, x)


梯度下降


接下来,我们编写梯度下降步骤来最大化目标类的记录可能性(或等价地,最小化交叉熵)。


  1. learning_rate = tf.placeholder(tf.float32, ())

  2. y_hat = tf.placeholder(tf.int32, ())

  3. labels = tf.one_hot(y_hat, 1000)

  4. loss = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=[labels])

  5. optim_step = tf.train.GradientDescentOptimizer(

  6.    learning_rate).minimize(loss, var_list=[x_hat])


投影步骤


最后,我们编写投影步骤来使对抗样本和原始图片看起来更接近。此外,我们会将图片剪辑为 [0,1],以让图片保持有效。


  1. epsilon = tf.placeholder(tf.float32, ())

  2. below = x - epsilon

  3. above = x + epsilon

  4. projected = tf.clip_by_value(tf.clip_by_value(x_hat, below, above), 0, 1)

  5. with tf.control_dependencies([projected]):

  6.    project_step = tf.assign(x_hat, projected)


执行


我们已准备好合成一个对抗样本图了,我们准备选择「鳄梨酱」(ImageNet 分类 924)来作为它的错误分类。


  1. demo_epsilon = 2.0/255.0 # a really small perturbation

  2. demo_lr = 1e-1

  3. demo_steps = 100

  4. demo_target = 924 # "guacamole"

  5. # initialization step

  6. sess.run(assign_op, feed_dict={x: img})

  7. # projected gradient descent

  8. for i in range(demo_steps):

  9.    # gradient descent step

  10.    _, loss_value = sess.run(

  11.        [optim_step, loss],

  12.        feed_dict={learning_rate: demo_lr, y_hat: demo_target})

  13.    # project step

  14.    sess.run(project_step, feed_dict={x: img, epsilon: demo_epsilon})

  15.    if (i+1) % 10 == 0:

  16.        print('step %d, loss=%g' % (i+1, loss_value))

  17. adv = x_hat.eval() # retrieve the adversarial example


  1. step 10, loss=4.18923

  2. step 20, loss=0.580237

  3. step 30, loss=0.0322334

  4. step 40, loss=0.0209522

  5. step 50, loss=0.0159688

  6. step 60, loss=0.0134457

  7. step 70, loss=0.0117799

  8. step 80, loss=0.0105757

  9. step 90, loss=0.00962179

  10. step 100, loss=0.00886694


这个对抗图片看起来和原图没什么区别,没有任何可见的人造痕迹。然而,它被明确地分类为「鳄梨酱」,而且置信度极高!


  1. classify(adv, correct_class=img_class, target_class=demo_target)




稳固的对抗样本


现在,让我们看看更高级的例子。我们遵循论文《Synthesizing Robust Adversarial Examples》的方法来寻找一个强大的对抗性样本,希望寻找到这张猫图片的单一扰动,让它在某些转变后仍然保持「假分类」。我们可以选择任何可微分变换的分布,在本文中,我们将演示图片如何在旋转θ∈[−π/4,π/4] 后保持对抗性输入。


在开始前,我们先检查一下刚才的对抗性样本在旋转后还管不管用,让我们旋转θ=π/8。


  1. ex_angle = np.pi/8

  2. angle = tf.placeholder(tf.float32, ())

  3. rotated_image = tf.contrib.image.rotate(image, angle)

  4. rotated_example = rotated_image.eval(feed_dict={image: adv, angle: ex_angle})

  5. classify(rotated_example, correct_class=img_class, target_class=demo_target)


看起来我们的原始对抗性样本不太管用了!




所以,如何让我们的对抗样本在旋转后仍有效果?给定变换 T 的分布,我们可以最大化 Et∼TlogP(y^∣t(x^)),使其服从∥x−x^∥∞≤ϵ。我们可以通过投影梯度下降来解决这个优化问题。注意,∇Et∼TlogP(y^∣t(x^)) 是 Et∼T∇logP(y^∣t(x^)) 并在每个梯度下降步骤中与样本近似。


与手动实现梯度采样不同,我们可以使用一个 trick 来让 TesnorFlow 为我们做到这点:我们可以对基于采样的梯度下降建模,作为随机分类器的集合中的梯度下降——在输入内容被分类前随机从分布和变化中采样。


  1. num_samples = 10

  2. average_loss = 0

  3. for i in range(num_samples):

  4.    rotated = tf.contrib.image.rotate(

  5.        image, tf.random_uniform((), minval=-np.pi/4, maxval=np.pi/4))

  6.    rotated_logits, _ = inception(rotated, reuse=True)

  7.    average_loss += tf.nn.softmax_cross_entropy_with_logits(

  8.        logits=rotated_logits, labels=labels) / num_samples


我们可以重新使用 assign_op 和 project_step 指令,尽管我们必须为这个新的目标写一个新的 optim_step。


  1. optim_step = tf.train.GradientDescentOptimizer(

  2.    learning_rate).minimize(average_loss, var_list=[x_hat])


最后,我们准备运行 PGD 来生成新的对抗输入。和刚才的例子一样,我们选择「鳄梨酱」来作为目标分类。


  1. demo_epsilon = 8.0/255.0 # still a pretty small perturbation

  2. demo_lr = 2e-1

  3. demo_steps = 300

  4. demo_target = 924 # "guacamole"

  5. # initialization step

  6. sess.run(assign_op, feed_dict={x: img})

  7. # projected gradient descent

  8. for i in range(demo_steps):

  9.    # gradient descent step

  10.    _, loss_value = sess.run(

  11.        [optim_step, average_loss],

  12.        feed_dict={learning_rate: demo_lr, y_hat: demo_target})

  13.    # project step

  14.    sess.run(project_step, feed_dict={x: img, epsilon: demo_epsilon})

  15.    if (i+1) % 50 == 0:

  16.        print('step %d, loss=%g' % (i+1, loss_value))

  17. adv_robust = x_hat.eval() # retrieve the adversarial example


  1. step 50, loss=0.0804289

  2. step 100, loss=0.0270499

  3. step 150, loss=0.00771527

  4. step 200, loss=0.00350717

  5. step 250, loss=0.00656128

  6. step 300, loss=0.00226182


完成了,这种对抗图片被分类为「鳄梨酱」,置信度很高,即使是在被旋转后也没问题!


  1. rotated_example = rotated_image.eval(feed_dict={image: adv_robust, angle: ex_angle})

  2. classify(rotated_example, correct_class=img_class, target_class=demo_target)



让我们评估一下所有角度旋转后的图片「鲁棒性」,看看从 P(y^∣x^) 在θ∈[−π/4,π/4] 角度中的效果。

  1. thetas = np.linspace(-np.pi/4, np.pi/4, 301)

  2. p_naive = []

  3. p_robust = []

  4. for theta in thetas:

  5.    rotated = rotated_image.eval(feed_dict={image: adv_robust, angle: theta})

  6.    p_robust.append(probs.eval(feed_dict={image: rotated})[0][demo_target])

  7.    rotated = rotated_image.eval(feed_dict={image: adv, angle: theta})

  8.    p_naive.append(probs.eval(feed_dict={image: rotated})[0][demo_target])

  9. robust_line, = plt.plot(thetas, p_robust, color='b', linewidth=2, label='robust')

  10. naive_line, = plt.plot(thetas, p_naive, color='r', linewidth=2, label='naive')

  11. plt.ylim([0, 1.05])

  12. plt.xlabel('rotation angle')

  13. plt.ylabel('target class probability')

  14. plt.legend(handles=[robust_line, naive_line], loc='lower right')

  15. plt.show()




如图所示,效果非常棒!


论文:Synthesizing Robust Adversarial Examples




论文链接:https://arxiv.org/abs/1707.07397


神经网络容易受到对抗性样本的影响:一点点精巧的扰动信息就可以让网络完全错判。然而,一些研究证明了这些对抗性样本在面对小小的转换之后就会失效:例如,放大图片就会让图像分类重新回归正确。这为我们带来了新的课题:在实践中,是否存在对抗性样本?因为在现实世界中,图像的远近和视角总是在不断变化的。


本论文证明了对抗性样本可以是鲁棒的——能够经受住各种变换的考验。我们的新方法可以让一张图片在经历所有变换之后仍然保持错误分类。实验证明,我们不能依赖缩放、转换和旋转来解决对抗性样本的问题。 


原文链接:http://www.anishathalye.com/2017/07/25/synthesizing-adversarial-examples/?utm_source=mybridge&utm_medium=blog&utm_campaign=read_more



本文为机器之心编译,转载请联系本公众号获得授权。

✄------------------------------------------------

加入机器之心(全职记者/实习生):hr@jiqizhixin.com

投稿或寻求报道:editor@jiqizhixin.com

广告&商务合作:bd@jiqizhixin.com

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存