Pytorch实现FGSM(FastGradientSignAttack)

Pytorch实现FGSM(FastGradientSignAttack)
⽬录
1. 相关说明
最近在整理相关实验代码的时候,⽆意中需要重新梳理下对抗攻击⾥的FGSM,于是⾃⼰参考⽹上的⼀些资料以及⾃⼰的⼼得写下这篇⽂章,⽤来以后回忆。
2. 相关简述
3. 代码实现
3.1 引⼊相关包
# 这句话的作⽤:即使是在Python2.7版本的环境下,print功能的使⽤格式也遵循Python3.x版本中的加括号的形式
from __future__ import print_function
import torch
as nn
张英森
functional as F
from torchvision import datasets, transforms
import numpy as np
import matplotlib.pyplot as plt
3.2 输⼊
# 设置不同扰动⼤⼩
epsilons =[0,.05,.1,.15,.2,.25,.3]
# 预训练模型
pretrained_model ="./data/lenet_mnist_model.pth"
植绒胶# 是否使⽤cuda
use_cuda =True
3.3 定义被攻击的模型
# 定义LeNet模型
class Net(nn.Module):
def__init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(320,50)
self.fc2 = nn.Linear(50,10)
def forward(self, x):
x = F.relu(F.max_v1(x),2))
x = F.relu(F.max_v2_v2(x)),2))
x = x.view(-1,320)
x = F.relu(self.fc1(x))
x = F.dropout(x, aining)
x = self.fc2(x)
return F.log_softmax(x, dim=1)
#声明 MNIST 测试数据集何数据加载
test_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=False, download=True, transform=transforms.Compose([            transforms.ToTensor(),
])),
batch_size=1, shuffle=True)
# 定义我们正在使⽤的设备
print("CUDA Available: ",torch.cuda.is_available())
device = torch.device("cuda"if(use_cuda and torch.cuda.is_available())else"cpu")
# 初始化⽹络
model = Net().to(device)
# 加载已经预训练的模型
model.load_state_dict(torch.load(pretrained_model, map_location='cpu'))
# 在评估模式下设置模型。在这种情况下,这适⽤于Dropout图层
model.eval()
然后我们运⾏下,出现下⾯结果,主要是在下载数据集。
3.4 定义FGSM攻击函数
# FGSM算法攻击代码
def fgsm_attack(image, epsilon, data_grad):
# 收集数据梯度的元素符号
sign_data_grad = data_grad.sign()
# 通过调整输⼊图像的每个像素来创建扰动图像usb token
perturbed_image = image + epsilon*sign_data_grad
# 添加剪切以维持[0,1]范围
perturbed_image = torch.clamp(perturbed_image,0,1)
# 返回被扰动的图像
return perturbed_image
3.5 测试函数
固化闪电之源
def test( model, device, test_loader, epsilon ):
# 精度计数器
correct =0
adv_examples =[]
自动感应垃圾桶
# 循环遍历测试集中的所有⽰例
for data, target in test_loader:
# 把数据和标签发送到设备
data, target = (device), (device)
# 设置张量的requires_grad属性,这对于攻击很关键
# 通过模型前向传递数据
output = model(data)
init_pred = output.max(1, keepdim=True)[1]# get the index of the max log-probability # 如果初始预测是错误的,不打断攻击,继续
if init_pred.item()!= target.item():
continue
# 计算损失
loss = F.nll_loss(output, target)
# 将所有现有的渐变归零
<_grad()
# 计算后向传递模型的梯度
loss.backward()
# 收集datagrad
data_grad = ad.data
# 唤醒FGSM进⾏攻击
perturbed_data = fgsm_attack(data, epsilon, data_grad)
# 重新分类受扰乱的图像
output = model(perturbed_data)
# 检查是否成功
final_pred = output.max(1, keepdim=True)[1]# get the index of the max log-probability if final_pred.item()== target.item():
correct +=1
# 保存0 epsilon⽰例的特例
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:
# 稍后保存⼀些⽤于可视化的⽰例
if len(adv_examples)<5:
adv_ex = perturbed_data.squeeze().detach().cpu().numpy()
adv_examples.append((init_pred.item(), final_pred.item(), adv_ex))
# 计算这个epsilon的最终准确度
final_acc = correct/float(len(test_loader))
print("Epsilon: {}\tTest Accuracy = {} / {} = {}".format(epsilon, correct,len(test_loader), final_acc)) # 返回准确性和对抗性⽰例
return final_acc, adv_examples
再次运⾏,输出下⾯结果:
Epsilon: 0 Test Accuracy = 9810 / 10000 = 0.981
Epsilon: 0.05 Test Accuracy = 9426 / 10000 = 0.9426 Epsilon: 0.1 Test Accuracy = 8510 / 10000 = 0.851 Epsilon: 0.15 Test Accuracy = 6826 / 10000 = 0.6826 Epsilon: 0.2 Test Accuracy = 4303 / 10000 = 0.4303 Epsilon: 0.25 Test Accuracy = 2087 / 10000 = 0.2087 Epsilon: 0.3 Test Accuracy = 871 / 10000 = 0.0871
4. 可视化结果
在上⾯的基础上我们添加下⾯的代码:
plt.figure(figsize=(5,5))
plt.plot(epsilons, accuracies,"*-")
注浆瓷器
plt.title("Accuracy vs Epsilon")
plt.xlabel("Epsilon")
plt.ylabel("Accuracy")
plt.show()
运⾏,出现下⾯结果:
5. 可视化对抗样本
# 在每个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)
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()
运⾏,结果如下:

本文发布于:2024-09-22 00:52:43,感谢您对本站的认可!

本文链接:https://www.17tex.com/tex/2/215575.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:攻击   模型   数据   图像   代码
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议