评价此页

对抗样本生成#

创建日期: 2018年8月14日 | 最后更新: 2025年1月27日 | 最后验证: 未验证

作者: Nathan Inkawhich

如果你正在阅读本文,希望你能理解机器学习模型在某些方面有多么高效。研究工作不断推动着机器学习模型变得更快、更准确且更高效。然而,在设计和训练模型时,安全性和鲁棒性往往被忽视,特别是在面对试图欺骗模型的攻击者时。

本教程将提高你对机器学习模型安全漏洞的认识,并深入探讨对抗性机器学习这一热门话题。你可能会惊讶地发现,向图像添加难以察觉的扰动竟然可以导致模型性能出现巨大的偏差。鉴于这是一个教程,我们将通过图像分类器的示例来探索这一主题。具体来说,我们将使用最早期且最流行的攻击方法之一——快速梯度符号攻击(Fast Gradient Sign Attack, FGSM)来欺骗一个 MNIST 分类器。

威胁模型#

背景说明:对抗性攻击分为许多类别,每种类别都有不同的目标和对攻击者知识的假设。然而,总的来说,其核心目标是在输入数据中添加最小量的扰动,从而导致预期的分类错误。关于攻击者知识的假设有多种,其中两种为:白盒(white-box)黑盒(black-box)白盒攻击假设攻击者拥有对模型的完全了解和访问权限,包括架构、输入、输出和权重。黑盒攻击假设攻击者仅能访问模型的输入和输出,对底层架构或权重一无所知。目标也有多种类型,包括误分类(misclassification)源/目标误分类(source/target misclassification)误分类的目标意味着对抗者只希望输出的分类是错误的,而不关心新的分类是什么。源/目标误分类意味着对抗者希望修改一张原本属于特定源类别的图像,使其被归类为特定的目标类别。

在本例中,FGSM 攻击是一种以误分类为目标的白盒攻击。有了这些背景信息,我们现在可以详细讨论该攻击。

快速梯度符号攻击#

迄今为止,最早且最流行的对抗性攻击之一被称为快速梯度符号攻击 (FGSM),由 Goodfellow 等人在 Explaining and Harnessing Adversarial Examples 一文中提出。这种攻击非常强大且直观。它旨在利用神经网络的学习方式——梯度,来对其进行攻击。其思想很简单:攻击不是通过基于反向传播的梯度调整权重来最小化损失,而是基于相同的反向传播梯度来调整输入数据,以最大化损失。换句话说,该攻击使用损失相对于输入数据的梯度,然后调整输入数据以最大化损失。

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

fgsm_panda_image

如图所示,\(\mathbf{x}\) 是被正确分类为“熊猫”的原始输入图像,\(y\)\(\mathbf{x}\) 的真实标签,\(\mathbf{\theta}\) 代表模型参数,而 \(J(\mathbf{\theta}, \mathbf{x}, y)\) 是用于训练网络的损失函数。该攻击将梯度反向传播回输入数据,以计算 \(\nabla_{x} J(\mathbf{\theta}, \mathbf{x}, y)\)。然后,它在会最大化损失的方向(即 \(sign(\nabla_{x} J(\mathbf{\theta}, \mathbf{x}, y))\))上,以一个小步长(图片中为 \(\epsilon\)\(0.007\))调整输入数据。产生的扰动图像 \(x'\) 随后被目标网络误分类为“长臂猿”,尽管它明显仍然是“熊猫”。

希望现在本教程的动机已经明确,让我们进入实现部分。

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import numpy as np
import matplotlib.pyplot as plt

实现#

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

输入#

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

  • epsilons - 用于运行的 epsilon 值列表。列表中保留 0 很重要,因为它代表了模型在原始测试集上的表现。此外,直觉上我们预计 epsilon 越大,扰动越明显,但攻击在降低模型准确率方面的效果就越好。由于这里的数据范围是 \([0,1]\),任何 epsilon 值都不应超过 1。

  • pretrained_model - 预训练 MNIST 模型的路径,该模型使用 pytorch/examples/mnist 进行训练。为简单起见,请点击此处下载预训练模型。

epsilons = [0, .05, .1, .15, .2, .25, .3]
pretrained_model = "data/lenet_mnist_model.pth"
# Set random seed for reproducibility
torch.manual_seed(42)
<torch._C.Generator object at 0x7f2d7fb3e2f0>

受攻击的模型#

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

# LeNet Model definition
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, 3, 1)
        self.conv2 = nn.Conv2d(32, 64, 3, 1)
        self.dropout1 = nn.Dropout(0.25)
        self.dropout2 = nn.Dropout(0.5)
        self.fc1 = nn.Linear(9216, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = self.conv1(x)
        x = F.relu(x)
        x = self.conv2(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2)
        x = self.dropout1(x)
        x = torch.flatten(x, 1)
        x = self.fc1(x)
        x = F.relu(x)
        x = self.dropout2(x)
        x = self.fc2(x)
        output = F.log_softmax(x, dim=1)
        return output

# MNIST Test dataset and dataloader declaration
test_loader = torch.utils.data.DataLoader(
    datasets.MNIST('../data', train=False, download=True, transform=transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize((0.1307,), (0.3081,)),
            ])),
        batch_size=1, shuffle=True)

# We want to be able to train our model on an `accelerator <https://pytorch.ac.cn/docs/stable/torch.html#accelerators>`__
# such as CUDA, MPS, MTIA, or XPU. If the current accelerator is available, we will use it. Otherwise, we use the CPU.
device = torch.accelerator.current_accelerator().type if torch.accelerator.is_available() else "cpu"
print(f"Using {device} device")

# Initialize the network
model = Net().to(device)

# Load the pretrained model
model.load_state_dict(torch.load(pretrained_model, map_location=device, weights_only=True))

# Set the model in evaluation mode. In this case this is for the Dropout layers
model.eval()
  0%|          | 0.00/9.91M [00:00<?, ?B/s]
100%|██████████| 9.91M/9.91M [00:00<00:00, 97.7MB/s]
100%|██████████| 9.91M/9.91M [00:00<00:00, 97.4MB/s]

  0%|          | 0.00/28.9k [00:00<?, ?B/s]
100%|██████████| 28.9k/28.9k [00:00<00:00, 41.3MB/s]

  0%|          | 0.00/1.65M [00:00<?, ?B/s]
100%|██████████| 1.65M/1.65M [00:00<00:00, 50.5MB/s]

  0%|          | 0.00/4.54k [00:00<?, ?B/s]
100%|██████████| 4.54k/4.54k [00:00<00:00, 29.2MB/s]
Using cuda device

Net(
  (conv1): Conv2d(1, 32, kernel_size=(3, 3), stride=(1, 1))
  (conv2): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1))
  (dropout1): Dropout(p=0.25, inplace=False)
  (dropout2): Dropout(p=0.5, inplace=False)
  (fc1): Linear(in_features=9216, out_features=128, bias=True)
  (fc2): Linear(in_features=128, out_features=10, bias=True)
)

FGSM 攻击#

现在,我们可以定义通过扰动原始输入来创建对抗样本的函数。 fgsm_attack 函数接收三个输入:image 是原始干净图像(\(x\)),epsilon 是像素级扰动量(\(\epsilon\)),data_grad 是损失相对于输入图像的梯度(\(\nabla_{x} J(\mathbf{\theta}, \mathbf{x}, y)\))。函数随后创建扰动图像为:

\[perturbed\_image = image + epsilon*sign(data\_grad) = x + \epsilon * sign(\nabla_{x} J(\mathbf{\theta}, \mathbf{x}, y)) \]

最后,为了保持数据的原始范围,扰动后的图像被裁剪到 \([0,1]\) 范围内。

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

# restores the tensors to their original scale
def denorm(batch, mean=[0.1307], std=[0.3081]):
    """
    Convert a batch of tensors to their original scale.

    Args:
        batch (torch.Tensor): Batch of normalized tensors.
        mean (torch.Tensor or list): Mean used for normalization.
        std (torch.Tensor or list): Standard deviation used for normalization.

    Returns:
        torch.Tensor: batch of tensors without normalization applied to them.
    """
    if isinstance(mean, list):
        mean = torch.tensor(mean).to(device)
    if isinstance(std, list):
        std = torch.tensor(std).to(device)

    return batch * std.view(1, -1, 1, 1) + mean.view(1, -1, 1, 1)

测试函数#

最后,本教程的核心结果来自 test 函数。对该测试函数的每次调用都会在 MNIST 测试集上执行完整的测试步骤并报告最终准确率。但是,请注意该函数也接受 epsilon 输入。这是因为 test 函数报告的是模型在强度为 \(\epsilon\) 的攻击者攻击下的准确率。更具体地说,对于测试集中的每个样本,该函数计算损失相对于输入数据的梯度(\(data\_grad\)),使用 fgsm_attack 创建扰动图像(\(perturbed\_data\)),然后检查该扰动样本是否具有对抗性。除了测试模型的准确率外,该函数还会保存并返回一些成功的对抗样本,以便稍后进行可视化。

def test( model, device, test_loader, epsilon ):

    # Accuracy counter
    correct = 0
    adv_examples = []

    # Loop over all examples in test set
    for data, target in test_loader:

        # Send the data and label to the device
        data, target = data.to(device), target.to(device)

        # Set requires_grad attribute of tensor. Important for Attack
        data.requires_grad = True

        # Forward pass the data through the model
        output = model(data)
        init_pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability

        # If the initial prediction is wrong, don't bother attacking, just move on
        if init_pred.item() != target.item():
            continue

        # Calculate the loss
        loss = F.nll_loss(output, target)

        # Zero all existing gradients
        model.zero_grad()

        # Calculate gradients of model in backward pass
        loss.backward()

        # Collect ``datagrad``
        data_grad = data.grad.data

        # Restore the data to its original scale
        data_denorm = denorm(data)

        # Call FGSM Attack
        perturbed_data = fgsm_attack(data_denorm, epsilon, data_grad)

        # Reapply normalization
        perturbed_data_normalized = transforms.Normalize((0.1307,), (0.3081,))(perturbed_data)

        # Re-classify the perturbed image
        output = model(perturbed_data_normalized)

        # Check for success
        final_pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability
        if final_pred.item() == target.item():
            correct += 1
            # Special case for saving 0 epsilon examples
            if epsilon == 0 and len(adv_examples) < 5:
                adv_ex = perturbed_data.squeeze().detach().cpu().numpy()
                adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex) )
        else:
            # Save some adv examples for visualization later
            if len(adv_examples) < 5:
                adv_ex = perturbed_data.squeeze().detach().cpu().numpy()
                adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex) )

    # Calculate final accuracy for this epsilon
    final_acc = correct/float(len(test_loader))
    print(f"Epsilon: {epsilon}\tTest Accuracy = {correct} / {len(test_loader)} = {final_acc}")

    # Return the accuracy and an adversarial example
    return final_acc, adv_examples

运行攻击#

实现部分的最后一部分是实际运行攻击。在这里,我们为 epsilons 输入中的每个 epsilon 值执行一个完整的测试步骤。对于每个 epsilon,我们还会保存最终的准确率和一些成功的对抗样本,以便在后续章节中绘图。注意观察随着 epsilon 值增加,打印出的准确率是如何下降的。此外,请注意 \(\epsilon=0\) 的情况代表没有攻击时的原始测试准确率。

accuracies = []
examples = []

# Run test for each epsilon
for eps in epsilons:
    acc, ex = test(model, device, test_loader, eps)
    accuracies.append(acc)
    examples.append(ex)
Epsilon: 0      Test Accuracy = 9873 / 10000 = 0.9873
Epsilon: 0.05   Test Accuracy = 9630 / 10000 = 0.963
Epsilon: 0.1    Test Accuracy = 9059 / 10000 = 0.9059
Epsilon: 0.15   Test Accuracy = 7793 / 10000 = 0.7793
Epsilon: 0.2    Test Accuracy = 5579 / 10000 = 0.5579
Epsilon: 0.25   Test Accuracy = 3254 / 10000 = 0.3254
Epsilon: 0.3    Test Accuracy = 1654 / 10000 = 0.1654

结果#

准确率与 Epsilon 的关系#

第一个结果是准确率与 epsilon 的关系图。正如前面所提到的,随着 epsilon 的增加,我们预期测试准确率会下降。这是因为 epsilon 越大,意味着我们在最大化损失的方向上迈出的步子越大。请注意,尽管 epsilon 值是线性间隔的,但曲线的趋势并非线性的。例如,\(\epsilon=0.05\) 时的准确率仅比 \(\epsilon=0\) 时低约 4%,但 \(\epsilon=0.2\) 时的准确率比 \(\epsilon=0.15\) 时低了 25%。此外,请注意该模型的准确率在 \(\epsilon=0.25\)\(\epsilon=0.3\) 之间达到了 10 类分类器的随机准确率水平。

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

对抗样本示例#

还记得“天下没有免费的午餐”这一概念吗?在本例中,随着 epsilon 的增加,测试准确率降低,但是扰动变得越来越明显。实际上,攻击者必须考虑准确率下降与可感知性之间的权衡。在这里,我们展示了每个 epsilon 值下成功对抗样本的一些例子。绘图的每一行显示不同的 epsilon 值。第一行是 \(\epsilon=0\) 的例子,代表没有扰动的原始“干净”图像。每张图片的标题显示了“原始分类 -> 对抗分类”。请注意,扰动在 \(\epsilon=0.15\) 时开始变得明显,在 \(\epsilon=0.3\) 时已经非常明显。然而,在所有情况下,人类尽管受到增加的噪声影响,仍然能够识别出正确的类别。

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

接下来做什么?#

希望本教程能对对抗性机器学习这一主题提供一些见解。从这里开始有很多潜在的发展方向。此攻击代表了对抗性攻击研究的起点,此后出现了许多针对如何攻击和防御机器学习模型免受对抗者侵害的后续想法。事实上,在 NIPS 2017 大会上,举办了一场对抗性攻击与防御竞赛,竞赛中使用的许多方法都描述在这篇论文中:Adversarial Attacks and Defences Competition。防御方面的研究也引出了如何使机器学习模型在面对自然扰动和人为构造的对抗输入时,整体上更加鲁棒的想法。

另一个方向是不同领域中的对抗性攻击与防御。对抗性研究并不局限于图像领域,请查看这篇针对语音转文本模型的攻击研究。但也许学习对抗性机器学习最好的方法是亲自动手。尝试实现 NIPS 2017 竞赛中另一种不同的攻击,看看它与 FGSM 有何不同。然后,尝试保护模型免受你自己发起的攻击。

根据可用资源,进一步的方向是修改代码以支持批量、并行或分布式处理工作,而不是像上面那样在每个 epsilon test() 循环中一次处理一个攻击。

脚本总运行时间: (2 分 29.732 秒)