PyTorch 对抗示例生成

2020-09-07 17:25 更新
原文: https://pytorch.org/tutorials/beginner/fgsm_tutorial.html

作者: Nathan Inkawhich

如果您正在阅读本文,希望您能体会到某些机器学习模型的有效性。 研究不断推动 ML 模型更快,更准确和更高效。 但是,设计和训练模型的一个经常被忽略的方面是安全性和鲁棒性,尤其是在面对想要欺骗模型的对手的情况下。

本教程将提高您对 ML 模型的安全漏洞的认识,并深入了解对抗性机器学习的热门话题。 您可能会惊讶地发现,在图像上添加无法察觉的扰动会导致导致完全不同的模型性能。 鉴于这是一个教程,我们将通过图像分类器上的示例来探讨该主题。 具体来说,我们将使用第一种也是最流行的攻击方法之一,即快速梯度符号攻击(FGSM)来欺骗 MNIST 分类器。

威胁模型

就上下文而言,有多种类型的对抗性攻击,每种攻击者的目标和假设都不同。 但是,总的来说,总体目标是向输入数据添加最少的扰动,以引起所需的错误分类。 攻击者的知识有几种假设,其中两种是:白盒和黑盒。 白盒攻击假定攻击者具有完整的知识并可以访问模型,包括体系结构,输入,输出和权重。 黑盒攻击假定攻击者仅有权访问模型的输入和输出,并且对底层体系结构或权重一无所知。 目标也有几种类型,包括错误分类和源/目标错误分类。 错误分类的目标是,这意味着对手只希望输出分类错误,而不在乎新分类是什么。 源/目标错误分类意味着对手想要更改最初属于特定源类别的图像,以便将其分类为特定目标类别。

在这种情况下,FGSM 攻击是白盒攻击,目标是错误分类。 有了这些背景信息,我们现在就可以详细讨论攻击了。

快速梯度符号攻击

迄今为止,最早的也是最流行的对抗性攻击之一称为快速梯度符号攻击(FGSM),由 Goodfellow 等描述。 等 中的解释和利用对抗性示例。 攻击非常强大,而且直观。 它旨在利用神经网络的学习方式梯度来攻击神经网络。 这个想法很简单,不是通过基于反向传播的梯度来调整权重来使损失最小化,攻击会基于相同的反向传播的梯度来调整输入数据以使损失最大化。 换句话说,攻击使用损失了输入数据的梯度,然后调整输入数据以使损失最大化。

在进入代码之前,让我们看一下著名的 FGSM 熊猫示例,并提取一些符号。

fgsm_panda_image

从图中可以看出, 是正确分类为“熊猫”的原始输入图像, 的地面真实标签, 代表模型参数, 是损失,即 用于训练网络。 攻击将梯度反向传播回输入数据以计算 。 然后,它会在使损失最大化的方向(即 )上以小步长(图片中的 )调整输入数据。 当目标网络仍然明显是“熊猫”时,目标网络将由此产生的扰动图像 误分类为为“长臂猿”。

希望本教程的动机已经明确,所以让我们跳入实施过程。

  1. from __future__ import print_function
  2. import torch
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. import torch.optim as optim
  6. from torchvision import datasets, transforms
  7. import numpy as np
  8. import matplotlib.pyplot as plt

实作

在本节中,我们将讨论本教程的输入参数,定义受攻击的模型,然后编写攻击代码并运行一些测试。

输入项

本教程只有三个输入,定义如下:

  • epsilons -用于运行的 epsilon 值列表。 在列表中保留 0 很重要,因为它表示原始测试集上的模型性能。 同样,从直觉上讲,我们期望ε越大,扰动越明显,但是从降低模型准确性的角度来看,攻击越有效。 由于此处的数据范围是 ,因此 epsilon 值不得超过 1。
  • pretrained_model -使用 pytorch / examples / mnist 训练的预训练 MNIST 模型的路径。 
  • use_cuda -布尔标志,如果需要和可用,则使用 CUDA。 请注意,具有 CUDA 的 GPU 在本教程中并不重要,因为 CPU 不会花费很多时间。
  1. epsilons = [0, .05, .1, .15, .2, .25, .3]
  2. pretrained_model = "data/lenet_mnist_model.pth"
  3. use_cuda=True

受到攻击的模型

如前所述,受到攻击的模型与 pytorch / examples / mnist 中的 MNIST 模型相同。 您可以训练并保存自己的 MNIST 模型,也可以下载并使用提供的模型。 这里的网络定义和测试数据加载器已从 MNIST 示例中复制而来。 本部分的目的是定义模型和数据加载器,然后初始化模型并加载预训练的权重。

  1. # LeNet Model definition
  2. class Net(nn.Module):
  3. def __init__(self):
  4. super(Net, self).__init__()
  5. self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
  6. self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
  7. self.conv2_drop = nn.Dropout2d()
  8. self.fc1 = nn.Linear(320, 50)
  9. self.fc2 = nn.Linear(50, 10)
  10. def forward(self, x):
  11. x = F.relu(F.max_pool2d(self.conv1(x), 2))
  12. x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
  13. x = x.view(-1, 320)
  14. x = F.relu(self.fc1(x))
  15. x = F.dropout(x, training=self.training)
  16. x = self.fc2(x)
  17. return F.log_softmax(x, dim=1)
  18. ## MNIST Test dataset and dataloader declaration
  19. test_loader = torch.utils.data.DataLoader(
  20. datasets.MNIST('../data', train=False, download=True, transform=transforms.Compose([
  21. transforms.ToTensor(),
  22. ])),
  23. batch_size=1, shuffle=True)
  24. ## Define what device we are using
  25. print("CUDA Available: ",torch.cuda.is_available())
  26. device = torch.device("cuda" if (use_cuda and torch.cuda.is_available()) else "cpu")
  27. ## Initialize the network
  28. model = Net().to(device)
  29. ## Load the pretrained model
  30. model.load_state_dict(torch.load(pretrained_model, map_location='cpu'))
  31. ## Set the model in evaluation mode. In this case this is for the Dropout layers
  32. model.eval()

得出:

  1. Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to ../data/MNIST/raw/train-images-idx3-ubyte.gz
  2. Extracting ../data/MNIST/raw/train-images-idx3-ubyte.gz to ../data/MNIST/raw
  3. Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz to ../data/MNIST/raw/train-labels-idx1-ubyte.gz
  4. Extracting ../data/MNIST/raw/train-labels-idx1-ubyte.gz to ../data/MNIST/raw
  5. Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz to ../data/MNIST/raw/t10k-images-idx3-ubyte.gz
  6. Extracting ../data/MNIST/raw/t10k-images-idx3-ubyte.gz to ../data/MNIST/raw
  7. Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz to ../data/MNIST/raw/t10k-labels-idx1-ubyte.gz
  8. Extracting ../data/MNIST/raw/t10k-labels-idx1-ubyte.gz to ../data/MNIST/raw
  9. Processing...
  10. Done!
  11. CUDA Available: True

FGSM 攻击

现在,我们可以通过干扰原始输入来定义创建对抗示例的函数。 fgsm_attack函数接受三个输入,图像是原始的干净图像( ), epsilon 是像素级扰动量( ),以及[HTG7 data_grad 是输入图像( )的损耗的梯度。 该函数然后创建扰动图像为

最后,为了维持数据的原始范围,将被摄动的图像裁剪为 范围。

  1. # FGSM attack code
  2. def fgsm_attack(image, epsilon, data_grad):
  3. # Collect the element-wise sign of the data gradient
  4. sign_data_grad = data_grad.sign()
  5. # Create the perturbed image by adjusting each pixel of the input image
  6. perturbed_image = image + epsilon*sign_data_grad
  7. # Adding clipping to maintain [0,1] range
  8. perturbed_image = torch.clamp(perturbed_image, 0, 1)
  9. # Return the perturbed image
  10. return perturbed_image

测试功能

最后,本教程的主要结果来自test函数。 每次调用此测试功能都会在 MNIST 测试集中执行完整的测试步骤,并报告最终精度。 但是,请注意,此功能还需要 epsilon 输入。 这是因为test函数报告了具有强度 的对手所攻击的模型的准确性。 更具体地说,对于测试集中的每个样本,该函数都会计算输入数据( )的损耗梯度,使用fgsm_attack( )创建一个扰动图像,然后检查是否受到扰动 例子是对抗性的。 除了测试模型的准确性外,该功能还保存并返回了一些成功的对抗示例,以供以后可视化。

  1. def test( model, device, test_loader, epsilon ):
  2. # Accuracy counter
  3. correct = 0
  4. adv_examples = []
  5. # Loop over all examples in test set
  6. for data, target in test_loader:
  7. # Send the data and label to the device
  8. data, target = data.to(device), target.to(device)
  9. # Set requires_grad attribute of tensor. Important for Attack
  10. data.requires_grad = True
  11. # Forward pass the data through the model
  12. output = model(data)
  13. init_pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability
  14. # If the initial prediction is wrong, dont bother attacking, just move on
  15. if init_pred.item() != target.item():
  16. continue
  17. # Calculate the loss
  18. loss = F.nll_loss(output, target)
  19. # Zero all existing gradients
  20. model.zero_grad()
  21. # Calculate gradients of model in backward pass
  22. loss.backward()
  23. # Collect datagrad
  24. data_grad = data.grad.data
  25. # Call FGSM Attack
  26. perturbed_data = fgsm_attack(data, epsilon, data_grad)
  27. # Re-classify the perturbed image
  28. output = model(perturbed_data)
  29. # Check for success
  30. final_pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability
  31. if final_pred.item() == target.item():
  32. correct += 1
  33. # Special case for saving 0 epsilon examples
  34. if (epsilon == 0) and (len(adv_examples) < 5):
  35. adv_ex = perturbed_data.squeeze().detach().cpu().numpy()
  36. adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex))
  37. else:
  38. # Save some adv examples for visualization later
  39. if len(adv_examples) < 5:
  40. adv_ex = perturbed_data.squeeze().detach().cpu().numpy()
  41. adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex))
  42. # Calculate final accuracy for this epsilon
  43. final_acc = correct/float(len(test_loader))
  44. print("Epsilon: {}\tTest Accuracy = {} / {} = {}".format(epsilon, correct, len(test_loader), final_acc))
  45. # Return the accuracy and an adversarial example
  46. return final_acc, adv_examples

奔跑攻击

实现的最后一部分是实际运行攻击。 在这里,我们为 epsilons 输入中的每个 epsilon 值运行完整的测试步骤。 对于每个 epsilon,我们还将保存最终精度,并在接下来的部分中绘制一些成功的对抗示例。 请注意,随着ε值的增加,打印的精度如何降低。 另外,请注意 的情况代表了原始的测试准确性,没有受到攻击。

  1. accuracies = []
  2. examples = []
  3. ## Run test for each epsilon
  4. for eps in epsilons:
  5. acc, ex = test(model, device, test_loader, eps)
  6. accuracies.append(acc)
  7. examples.append(ex)

得出:

  1. Epsilon: 0 Test Accuracy = 9810 / 10000 = 0.981
  2. Epsilon: 0.05 Test Accuracy = 9426 / 10000 = 0.9426
  3. Epsilon: 0.1 Test Accuracy = 8510 / 10000 = 0.851
  4. Epsilon: 0.15 Test Accuracy = 6826 / 10000 = 0.6826
  5. Epsilon: 0.2 Test Accuracy = 4301 / 10000 = 0.4301
  6. Epsilon: 0.25 Test Accuracy = 2082 / 10000 = 0.2082
  7. Epsilon: 0.3 Test Accuracy = 869 / 10000 = 0.0869

结果

精度与 Epsilon

第一个结果是精度与ε曲线的关系。 如前所述,随着ε的增加,我们期望测试精度会降低。 这是因为较大的ε意味着我们朝着将损失最大化的方向迈出了更大的一步。 请注意,即使 epsilon 值是线性间隔的,曲线中的趋势也不是线性的。 例如,在  处的精度仅比  低约 4%,但在  处的精度比   低 25%。 另外,请注意,对于  和  之间的 10 类分类器,模型的准确性达到了随机准确性。

  1. plt.figure(figsize=(5,5))
  2. plt.plot(epsilons, accuracies, "*-")
  3. plt.yticks(np.arange(0, 1.1, step=0.1))
  4. plt.xticks(np.arange(0, .35, step=0.05))
  5. plt.title("Accuracy vs Epsilon")
  6. plt.xlabel("Epsilon")
  7. plt.ylabel("Accuracy")
  8. plt.show()

../_images/sphx_glr_fgsm_tutorial_001.png

对抗示例

还记得没有免费午餐的想法吗? 在这种情况下,随着 ε 的增加,测试精度降低,但的扰动变得更容易察觉。 实际上,在攻击者必须考虑的准确性下降和可感知性之间要进行权衡。 在这里,我们展示了每个 epsilon 值的成功对抗示例。 绘图的每一行显示不同的ε值。 第一行是  示例,代表原始的“干净”图像,没有干扰。 每张图像的标题均显示“原始分类->对抗分类”。 注意,扰动开始在  变得明显,并且在 变得非常明显。 然而,在所有情况下,尽管噪声增加,人类仍然能够识别正确的类别。

  1. # Plot several examples of adversarial samples at each epsilon
  2. cnt = 0
  3. plt.figure(figsize=(8,10))
  4. for i in range(len(epsilons)):
  5. for j in range(len(examples[i])):
  6. cnt += 1
  7. plt.subplot(len(epsilons),len(examples[0]),cnt)
  8. plt.xticks([], [])
  9. plt.yticks([], [])
  10. if j == 0:
  11. plt.ylabel("Eps: {}".format(epsilons[i]), fontsize=14)
  12. orig,adv,ex = examples[i][j]
  13. plt.title("{} -> {}".format(orig, adv))
  14. plt.imshow(ex, cmap="gray")
  15. plt.tight_layout()
  16. plt.show()

../_images/sphx_glr_fgsm_tutorial_002.png

接下来要去哪里?

希望本教程对对抗性机器学习主题有所了解。 从这里可以找到许多潜在的方向。 这种攻击代表了对抗性攻击研究的最开始,并且由于随后有许多关于如何攻击和防御来自对手的 ML 模型的想法。 实际上,在 NIPS 2017 上有一个对抗性的攻击和防御竞赛,并且本文描述了该竞赛中使用的许多方法:对抗性的攻击与防御竞赛。 国防方面的工作还引发了使机器学习模型总体上更健壮健壮的想法,以适应自然扰动和对抗制造的输入。

另一个方向是不同领域的对抗性攻击和防御。 对抗性研究不仅限于图像领域,请查看对语音到文本模型的这种攻击。 但是,也许更多地了解对抗性机器学习的最好方法是弄脏您的手。 尝试实施与 NIPS 2017 竞赛不同的攻击,并查看其与 FGSM 的不同之处。 然后,尝试保护模型免受自己的攻击。

脚本的总运行时间:(3 分钟 14.922 秒)

Download Python source code: fgsm_tutorial.py Download Jupyter notebook: fgsm_tutorial.ipynb

由狮身人面像画廊生成的画廊


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号