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

news2024/11/19 22:54:20

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

一、威胁模型

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

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/10970.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Reactor 模型

文章目录1、网络编程关注的事件2、网络 IO 的职责2.1、IO 检测2.1.1、连接建立2.1.2、连接断开2.1.3、消息到达2.1.4、消息发送2.2、IO 操作2.2.1、连接建立2.2.2、连接断开2.2.3、连接到达2.2.4、消息发送3、Reactor 模式3.1、概念3.2、面试&#xff1a;Reactor 为什么使用非阻…

利用jenkins直接构件docker镜像并发布

一、本服务器构建 1.jenkins安装完成之后&#xff0c;打jenkins&#xff0c;选择新建任务&#xff0c;如&#xff1a; 2.进行〔源码管理〕配置&#xff0c;如&#xff1a; 3.构建执行配置&#xff0c;如&#xff1a; APP_NAMEtest-project APP_PORT8083 RUN_ENVprod cd /var/…

EtherCAT与RTEX驱动器轴回零的配置与实现

上节课程&#xff0c;正运动小助手给大家分享了运动控制器提供的回零模式配置与实现。本节课程主要介绍控制器实现EtherCAT与RTEX驱动器的回零及其配置。 01 总线驱动器回零模式 正运动控制器提供自己的回零模式&#xff0c;也支持使用EtherCAT总线驱动器提供的回零模式&…

学长教你学C-day9-C语言循环结构与选择结构

小刘最近在读《老子》&#xff0c;被道家“一生二&#xff0c;二生三”的哲学思想迷住了&#xff0c;他不禁想代码是谁生的呢&#xff1f;首先代码就是一堆字符&#xff0c;字符不是代码&#xff0c;就像“白马非马”&#xff0c;但是当字符按照一定的顺序组织起来时&#xff0…

《Python编程无师自通》读书笔记

不能越界访问函数内部定义的变量 global不能乱用 啥时候用元组 join连接 小点&#xff0c;但第一次见会觉得蛮有意思。 Hangman 10.1的案例蛮有意思的 一搜才发现是十分经典的文字游戏 过程式编程的缺点以及函数式编程和面向对象编程的解决方法 过程式编程的缺点 函数式编程…

Web学习笔记-中期项目(拳皇)

CONTENTS项目原理一、基础文件二、ac_game_object框架三、游戏地图与玩家模型的创建项目原理 游戏中一个物体运动的原理是浏览器每秒钟刷新60次&#xff0c;每次我们单独计算这个物体新的位置&#xff0c;然后把他刷新出来&#xff0c;这样最终人眼看起来就是移动的效果。 对…

YOLO系列概述(yolov1至yolov7)

YOLO系列概述&#xff08;yolov1至yolov7&#xff09; 参考&#xff1a; 睿智的目标检测53——Pytorch搭建YoloX目标检测平台YoloV7 yolo的发展历史 首先我们来看一下yolo系列的发展历史&#xff0c;yolo v1和yolox是anchor free的方法&#xff0c;yolov2&#xff0c;yolov3…

使用 Vue3 实现锚点组件

目录 1. 需求介绍 2. 实现过程 2.1 表单结构介绍 2.2 确定锚点组件接收的参数及使用方法 2.2.1 form-dom&#xff1a;需要被锚点组件控制的表单实例 2.2.2 active-anchor&#xff1a;默认激活的锚点 2.2.3 title-class&#xff1a;表单标题特有的类名 2.2.4 将 锚点组件…

5-FITC,5-FITC(isomer I),5-异硫氰酸荧光素,5-Flourescein iso-thiocyanate

产品名称&#xff1a;5-FITC&#xff0c;5-异硫氰酸荧光素 英文名称&#xff1a;5-Flourescein iso-thiocyanate 英文别名&#xff1a;5-FITC&#xff1b;5-Flourescein iso-thiocyanate&#xff1b;FITC Isomer I [5-FITC; fluorescein-5-isothiocyanate] CAS#&#xff1a;…

labview 串口通信 modbusRtu

在自动化或测试项目中&#xff0c;上位机软件需要和PLC及仪表通信&#xff0c;本文简单描述这个问题。 1.在程序框图中放置4个图标 &#xff08;1&#xff09;创建modbus 主站实例&#xff08;按如下图标识①,在框图中放Create Master Instance.vi) 图1 放置四个图标 &…

C++ Reference: Standard C++ Library reference: Containers: deque: deque: resize

C官网参考链接&#xff1a;https://cplusplus.com/reference/deque/deque/resize/ 公有成员函数 <deque> std::deque::resize C98 void resize (size_type n, value_type val value_type()); C11 void resize (size_type n); void resize (size_type n, const value_t…

React组件复用

mixins&#xff08;已废弃&#xff09; https://react.docschina.org/blog/2016/07/13/mixins-considered-harmful.html mixin引入了隐式依赖关系 对于组件中的方法和数据的来源不明确&#xff0c;不容易维护 Mixins 导致名称冲突Mixins 导致滚雪球般的复杂性 render-props技术…

C语言学习之路(基础篇)—— 指针(上)

说明&#xff1a;该篇博客是博主一字一码编写的&#xff0c;实属不易&#xff0c;请尊重原创&#xff0c;谢谢大家&#xff01; 概述 1) 内存 内存含义&#xff1a; 存储器&#xff1a; 计算机的组成中&#xff0c;用来存储程序和数据&#xff0c;辅助CPU进行运算处理的重要…

python切分TXT的句子到Excel(复制可用)——以及python切分句子遇到的问题汇总

文章目录完整代码时间转化和提取各种对象类型转换时间序列类属性数据转换完整代码 import jieba.analyseimport jieba.posseg as pseg from wordcloud import WordCloud import xlsxwriter # encodinggbk import xlsxwriterf open(E:/data/xieyangteng/review.txt, r, encodi…

波的相关参数概念整理

频率&#xff08;frequency&#xff09;&#xff0c;符号f&#xff0c;表示单位时间内完成周期性变化的次数。f1/T&#xff0c;单位s-1 角频率&#xff0c;符号ω&#xff0c;表示单位时间内变化的角弧度值。ω 2πf 2π/T,单位rad/s 波长&#xff08;wavelength&#xff0…

<SQL编程工具MySQL、SQLyog安装及环境配置教程>——《SQL》

目录 1.MySQL安装&#xff1a; 1.1 MySQL下载安装&#xff1a; 1.2 MySQL环境变量配置&#xff1a; 2.SQLyog安装&#xff1a; 2.1 SQLyog下载安装&#xff1a; 3.写在最后的话&#xff1a; 后记&#xff1a;●由于作者水平有限&#xff0c;文章难免存在谬误之处&…

力扣刷题day49|647回文子串、516最长回文子序列

文章目录647. 回文子串思路暴力解法动态规划五部曲516. 最长回文子序列思路动态规划五部曲647. 回文子串 力扣题目链接 给你一个字符串 s &#xff0c;请你统计并返回这个字符串中 回文子串 的数目。 回文字符串 是正着读和倒过来读一样的字符串。 子字符串 是字符串中的由…

代码随想录算法训练营第一天|LeetCode704二分查找、LeetCode27移除元素

LeetCode704二分查找 题目链接&#xff1a;704二分查找 思路&#xff1a; 以前刷过不少题&#xff0c;也看过不少题解&#xff0c;就记得区间有不少原则&#xff0c;乍一想有哪些想不起来了&#xff0c;反正我是选择了最简单易懂的左闭右闭原则。 1、区间左闭右闭原则。 2、w…

SpringBoot SpringBoot 开发实用篇 2 配置高级 2.3 常用计量单位应用

SpringBoot 【黑马程序员SpringBoot2全套视频教程&#xff0c;springboot零基础到项目实战&#xff08;spring boot2完整版&#xff09;】 SpringBoot 开发实用篇 文章目录SpringBootSpringBoot 开发实用篇2 配置高级2.3 常用计量单位应用2.3.1 问题引入2.3.2 常用计量单位应…

实验2 存储器设计与实现【计算机组成原理】

实验2 存储器设计与实现【计算机组成原理】实验2 存储器设计与实现一、实验目的二、实验环境三、实验原理四、实验任务五、实验结果&#xff1a;六、心得体会&#xff1a;实验2 存储器设计与实现 一、实验目的 掌握单端口RAM和ROM原理和设计方法。掌握32位数据的读出和写入方…