PyTorch使用快速梯度符号攻击(FGSM)实现对抗性样本生成(附源码和数据集MNIST手写数字)

需要源码和数据集请点赞关注收藏后评论区留言或者私信~~~

一、威胁模型

对抗性机器学习,意思是在训练的模型中添加细微的扰动最后会导致模型性能的巨大差异,接下来我们通过一个图像分类器上的示例来进行讲解,具体的说,会使用第一个也是最流行的攻击方法之一,快速梯度符号攻击来欺骗一个MNIST分类器

每一类攻击都有不同的目标和对攻击者知识的假设,总的目标是在输入数据中添加最少的扰动,以导致所需要的错误分类。攻击有两者假设,分别是黑盒与白盒

1:白盒攻击假设攻击者具有对模型的全部知识和访问权,包括体系结构,输入,输出和权重。

2:黑盒攻击假设攻击者只访问模型的输入和输出,对底层架构或权重一无所知

FGSM攻击是一种以错误分类为目标的白盒攻击

二、快速梯度符号攻击简介 

FGSM直接利用神经网络的学习方式--梯度更新来攻击神经网络,这种攻击时根据相同的反向传播梯度调整输入数据来最大化损失,换句话说,攻击使用了输入数据相关的梯度损失方式,通过调整输入数据,使损失最大化。

三、输入

对抗样本模型只有三个输入 定义如下

1:epsilons 用于运行的epsilon值列表,在列表中保留0很重要,因为它代表原始测试集上的模型性能

2:pretrained_model  使用mnist训练的预训练MNIST模型的路径 可自行下载

3:use_cuda  布尔标志 如果需要和可用,则使用CUDA 其实不用也行 因为用CPU也不会花费太多时间

四、FGSM攻击 

介绍完上面的基本知识之后,可以通过干扰原始输入来定义创建对抗示例的函数,它需要三个输入分别为图像是干净的原始图像,epsilon是像素方向的扰动量,data_grad是输入图片

攻击函数代码如下

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输入中的每个值运行测试,随着值的增加,打印的精度逐渐降低

 五、结果分析

第一个结果是accuracy与参数曲线的关系,可以看到,随着参数的增加,我们期望测试精度会降低,这是因为较大的参数意味着我们朝着将损失最大化的方向迈出了更大的一步 结果如下

 六、对抗示例

系统性学习过计算机的小伙伴们应该对tradeoff这个词并并不陌生,它意味着权衡,如上图所示,随着参数的增加,测试精度降低,但是同时扰动变得更加易于察觉,这里攻击者就要考虑准确性降低和可感知性之间的权衡。接下来将展示不同epsilon值的成功对抗

参数等于0时为原始干净且无扰动时的图像,可以看到,扰动在参数为0.15和0.3时变得明显

 七、代码

部分源码如下



# In[1]:


from __future__ import print_function
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





# 
# -  **pretrained_model** - path to the pretrained MNIST model which was
#    trained with
#    `pytorch/examples/mnist <https://github.com/pytorch/examples/tree/master/mnist>`__.
#    For simplicity, download the pretrained model `here <https://drive.google.com/drive/folders/1fn83DF14tWmit0RTKWRhPq5uVXt73e0h?usp=sharing>`__.
# 



# In[9]:


epsilons = [0, .05, .1, .15, .2, .25, .3]
pretrained_model = "data/lenet_mnist_model.pth"
use_cuda=True


# Model Under Attack
# ~~~~~~~~~~~~~~~~~~
# 
# As mentioned, the model under attack is the same MNIST model from
# `pytorch/examples/mnist <https://github.com/pytorch/examples/tree/master/mnist>`__.
# You may train and save your own MNIST model or you can download and use
# the provided model. The *Net* definition and test dataloader here have
# been copied from the MNIST example. The purpose of this section is to
# define the model and dataloader, then initialize the model and load the
# pretrained weights.
# 
# 
# 

# In[3]:


# LeNet Model definition

        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
        self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
        self.conv2_drop = nn.Dropout2d()
        self.fc1 = nn.Linear(320, 50)
        self.fc2 = nn.Linear(50, 10)

    d
        return F.log_softmax(x, dim=1)

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

# Define what device we are using
print("CUDA Available: ",torch.cuda.is_available())
device = torch.device("cuda" if (use_cuda and torch.cuda.is_available()) else "cpu")

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

# Load the pretrained model
model.load_state_dict(torch.load(pretrained_model, map_location='cpu'))

# Set the model in evaluation mode. In this case this is for the Dropout layers
model.eval()


ginal inputs. The ``fgsm_attack`` function takes three
# inputs, *image* is the original clean image ($x$), *epsilon* is
# the pixel-wise perturbation amount ($\epsilon$), and *data_grad*
# is gradient of the loss w.r.t the input image
# ($\nabla_{x} J(\mathbf{\theta}, \mathbf{x}, y)$). The function
# then creates perturbed image as
# 
# \begin{align}perturbed\_image = image + epsilon*sign(data\_grad) = x + \epsilon * sign(\nabla_{x} J(\mathbf{\theta}, \mathbf{x}, y))\end{align}
# 
# Finally, in order to maintain the original range of the data, the
# perturbed image is clipped to range $[0,1]$.
# 
# 
# 

# In[4]:


#= 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


# Testing Function
# ~~~~~~~~~~~~~~~~
# 
# Finally, the central result of this tutorial comes from the ``test``
# function. Each call to this test function performs a full test step on
# the MNIST test set and reports a final accuracy. However, notice that
# this function also takes an *epsilon* input. This is because the
# ``test`` function reports the accuracy of a model that is under attack
# from an adversary with strength $\epsilon$. More specifically, for
# each sample in the test set, the function computes the gradient of the
# loss w.r.t the input data ($data\_grad$), creates a perturbed
# image with ``fgsm_attack`` ($perturbed\_data$), then checks to see
# if the perturbed example is adversarial. In addition to testing the
# accuracy of the model, the function also saves and returns some
# successful adversarial examples to be visualized later.
# 
# 
# 

# In[5]:


t = 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, dont 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

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

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

        # 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("Epsilon: {}\tTest Accuracy = {} / {} = {}".format(epsilon, correct, len(test_loader), final_acc))
al_acc, adv_examples


# Run Attack
# ~~~~~~~~~~
# 
# The last part of the implementation is to actually run the attack. Here,
# we run a full test step for each epsilon value in the *epsilons* input.
# For each epsilon we also save the final accuracy and some successful
# adversarial examples to be plotted in the coming sections. Notice how
# the printed accuracies decrease as the epsilon value increases. Also,
# note the $\epsilon=0$ case represents the original test accuracy,
# with no attack.
# 
# 
# 

# In[6]:


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)


# Results
# -------
# 
# Accuracy vs Epsilon
# ~~~~~~~~~~~~~~~~~~~
# 
# The first result is the accuracy versus epsilon plot. As alluded to
# earlier, as epsilon increases we expect the test accuracy to decrease.
# This is because larger epsilons mean we take a larger step in the
# direction that will maximize the loss. Notice the trend in the curve is
# not linear even though the epsilon values are linearly spaced. For
# example, the accuracy at $\epsilon=0.05$ is only about 4% lower
# than $\epsilon=0$, but the accuracy at $\epsilon=0.2$ is 25%
# lower than $\epsilon=0.15$. Also, notice the accuracy of the model
# hits random accuracy for a 10-class classifier between
# $\epsilon=0.25$ and $\epsilon=0.3$.
# 
# 
# 

# In[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()


# Sample Adversarial Examples
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~
# 
# Remember the idea of no free lunch? In this case, as epsilon increases
# the test accuracy decreases **BUT** the perturbations become more easily
# perceptible. In reality, there is a tradeoff between accuracy
# degredation and perceptibility that an attacker must consider. Here, we
# show some examples of successful adversarial examples at each epsilon
# value. Each row of the plot shows a different epsilon value. The first
# row is the $\epsilon=0$ examples which represent the original
# “clean” images with no perturbation. The title of each image shows the
# “original classification -> adversarial classification.” Notice, the
# perturbations start to become evident at $\epsilon=0.15$ and are
# quite evident at $\epsilon=0.3$. However, in all cases humans are
# still capable of identifying the correct class despite the added noise.
# 
# 
# 

# In[11]:


# 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("Eps: {}".format(epsilons[i]), fontsize=14)
        orig,adv,ex = examples[i][j]
        plt.title("{} -> {}".format(orig, adv))
        plt.imshow(ex, cmap="gray")
plt.tight_layout()
plt.show()


# Where to go next?
# -----------------
# 
# Hopefully this tutorial gives some insight into the topic of adversarial
# machine learning. There are many potential directions to go from here.
# This attack represents the very beginning of adversarial attack research
# and since there have been many subsequent ideas for how to attack and
# defend ML models from an adversary. In fact, at NIPS 2017 there was an
# adversarial attack and defense competition and many of the methods used
# in the competition are described in this paper: `Adversarial Attacks and
# Defences Competition <https://arxiv.org/pdf/1804.00097.pdf>`__. The work
# on defense also leads into the idea of making machine learning models
# more *robust* in general, to both naturally perturbed and adversarially
# crafted inputs.
# 
# Another direction to go is adversarial attacks and defense in different
# domains. Adversarial research is not limited to the image domain, check
# out `this <https://arxiv.org/pdf/1801.01944.pdf>`__ attack on
# speech-to-text models. But perhaps the best way to learn more about
# adversarial machine learning is to get your hands dirty. Try to
# implement a different attack from the NIPS 2017 competition, and see how
# it differs from FGSM. Then, try to defend the model from your own
# attacks.
# 
# 
# 

创作不易 觉得有帮助请点赞关注收藏~~~

  • 17
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 19
    评论
### 回答1: FGSM(Fast Gradient Sign Method)是一种用于生成对抗样本的方,基于pytorch可以很方便地实现。 首先,我们需要一个已经训练好的模型,可以是一个分类模型或者其他类型的模型。然后,我们通过计算模型的损失函数对输入数据进行求导。根据求导结果,我们可以得到一个关于输入数据的梯度。接下来,我们根据梯度的方向来对输入数据进行扰动,生成对抗样本。 下面是一个基于pytorch的FGSM对抗样本实现: ```python import torch import torch.nn as nn import torch.optim as optim def fgsm_attack(model, loss_fn, epsilon, input_data, target_label): input_data.requires_grad = True model.eval() output = model(input_data) loss = loss_fn(output, target_label) model.zero_grad() loss.backward() input_grad = input_data.grad.data modified_data = input_data + epsilon * torch.sign(input_grad) modified_data = torch.clamp(modified_data, 0, 1) return modified_data # 定义一个简单的模型 class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.fc = nn.Linear(784, 10) def forward(self, x): x = x.view(x.size(0), -1) x = self.fc(x) return x if __name__ == '__main__': # 加载模型 model = Model() model.load_state_dict(torch.load('model.pt')) model.eval() # 加载数据 input_data, target_label = load_data() # 定义损失函数 loss_fn = nn.CrossEntropyLoss() # 设置epsilon epsilon = 0.1 modified_data = fgsm_attack(model, loss_fn, epsilon, input_data, target_label) # 对抗样本的输出 output = model(modified_data) print(output) ``` 以上代码是一个基于pytorch的FGSM对抗样本生成的简单示例。我们首先加载已经训练好的模型,然后通过调用fgsm_attack函数生成对抗样本。最后,我们使用修改后的输入数据来获得模型的输出。对抗样本可以通过在输入数据上添加一个与目标梯度方向相反、大小为epsilon的扰动来产生。 ### 回答2: FGSM(Fast Gradient Sign Method)是一种基于梯度信息的对抗样本生成,可以用于攻击深度学习模型。而基于PyTorch实现,可以轻松地利用PyTorch的自动求导功能来计算模型的梯度信息。 首先,我们需要定义PyTorch模型,并加载训练好的模型参数。然后,我们可以定义一个函数来生成对抗样本。对于给定的输入样本,我们首先计算其对应的损失函数,并使用自动求导来计算损失函数对输入样本梯度。接下来,我们根据梯度符号来产生扰动,从而生成对抗样本。最后,我们可以使用生成的对抗样本来对深度学习模型进行攻击。 FGSM对抗样本生成的具体步骤如下: 1. 定义PyTorch模型,并加载模型参数。 2. 对于给定的输入样本,将其输入模型得到输出。 3. 计算输入样本对应的损失函数,并使用自动求导来计算损失函数对输入样本梯度。 4. 根据输入样本梯度符号来产生扰动,这里的扰动大小可以通过指定的epsilon值来控制。 5. 将扰动添加到输入样本上,生成对抗样本。 6. 使用生成的对抗样本来对深度学习模型进行攻击,观察对抗样本的分类结果。 总之,PyTorch提供了便捷的梯度计算和自动求导功能,使得基于FGSM的对抗样本生成变得简单。使用PyTorch实现的FGSM可以用于研究深度学习模型的鲁棒性以及对抗攻击的防御方。 ### 回答3: 基于PyTorch的Fast Gradient Sign Method(FGSM)是一种常用的对抗样本生成。FGSM利用损失函数相对于输入数据的梯度信息来构造对抗样本,从而欺骗深度学习模型。 在PyTorch使用FGSM生成对抗样本,需要以下几个步骤: 1. 加载和准备数据:首先通过PyTorch加载原始数据集,并对其进行预处理和归一化。 2. 定义模型:使用PyTorch定义一个希望攻击深度学习模型。 3. 计算损失函数:通过对原始图像调用模型,计算出其预测结果,然后使用PyTorch的损失函数计算原始图像的损失。 4. 计算梯度:通过调用PyTorch的反向传播函数,计算原始图像关于损失的梯度。 5. 生成对抗样本使用计算得到的梯度信息来扰动原始图像,添加一个扰动项,以便欺骗模型。扰动项的大小由一个称为epsilon的参数控制,它是我们人为设置的一个很小的值。 6. 确定对抗样本:通过将扰动项加到原始图像上,得到对抗样本。 值得注意的是,对抗样本生成是为了误导模型而不影响人类的视觉感知。为了保持对抗样本和原始样本之间的可转移性,我们通常在epsilon的范围内限制扰动项的值。 最后,可以使用生成的对抗样本来测试被攻击模型的鲁棒性,即观察它是否在面对对抗样本时能够准确预测。如果鲁棒性下降,说明模型可能容易受到攻击,并需要采取相应的防御措施。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

showswoller

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值