Pytorch | 利用VA-I-FGSM针对CIFAR10上的ResNet分类器进行对抗攻击
- CIFAR数据集
- VA-I-FGSM介绍
- 相关定义
- 算法流程
- VAI-FGSM代码实现
- VAI-FGSM算法实现
- 攻击效果
- 代码汇总
- vaifgsm.py
- train.py
- advtest.py
之前已经针对CIFAR10训练了多种分类器:
Pytorch | 从零构建AlexNet对CIFAR10进行分类
Pytorch | 从零构建Vgg对CIFAR10进行分类
Pytorch | 从零构建GoogleNet对CIFAR10进行分类
Pytorch | 从零构建ResNet对CIFAR10进行分类
Pytorch | 从零构建MobileNet对CIFAR10进行分类
Pytorch | 从零构建EfficientNet对CIFAR10进行分类
Pytorch | 从零构建ParNet对CIFAR10进行分类
也实现了一些攻击算法:
Pytorch | 利用FGSM针对CIFAR10上的ResNet分类器进行对抗攻击
Pytorch | 利用BIM/I-FGSM针对CIFAR10上的ResNet分类器进行对抗攻击
Pytorch | 利用MI-FGSM针对CIFAR10上的ResNet分类器进行对抗攻击
Pytorch | 利用NI-FGSM针对CIFAR10上的ResNet分类器进行对抗攻击
Pytorch | 利用PI-FGSM针对CIFAR10上的ResNet分类器进行对抗攻击
Pytorch | 利用VMI-FGSM针对CIFAR10上的ResNet分类器进行对抗攻击
Pytorch | 利用VNI-FGSM针对CIFAR10上的ResNet分类器进行对抗攻击
Pytorch | 利用EMI-FGSM针对CIFAR10上的ResNet分类器进行对抗攻击
Pytorch | 利用AI-FGTM针对CIFAR10上的ResNet分类器进行对抗攻击
Pytorch | 利用I-FGSSM针对CIFAR10上的ResNet分类器进行对抗攻击
Pytorch | 利用SMI-FGRM针对CIFAR10上的ResNet分类器进行对抗攻击
本篇文章我们使用Pytorch实现VA-I-FGSM对CIFAR10上的ResNet分类器进行攻击.
CIFAR数据集
CIFAR-10数据集是由加拿大高级研究所(CIFAR)收集整理的用于图像识别研究的常用数据集,基本信息如下:
- 数据规模:该数据集包含60,000张彩色图像,分为10个不同的类别,每个类别有6,000张图像。通常将其中50,000张作为训练集,用于模型的训练;10,000张作为测试集,用于评估模型的性能。
- 图像尺寸:所有图像的尺寸均为32×32像素,这相对较小的尺寸使得模型在处理该数据集时能够相对快速地进行训练和推理,但也增加了图像分类的难度。
- 类别内容:涵盖了飞机(plane)、汽车(car)、鸟(bird)、猫(cat)、鹿(deer)、狗(dog)、青蛙(frog)、马(horse)、船(ship)、卡车(truck)这10个不同的类别,这些类别都是现实世界中常见的物体,具有一定的代表性。
下面是一些示例样本:
VA-I-FGSM介绍
VA-I-FGSM(Virtual Step and Auxiliary Gradients Iterative Fast Gradient Sign Method)是一种用于生成对抗样本的算法,旨在提高对抗样本在不同模型之间的转移性。以下是VA-I-FGSM算法的详细介绍:
相关定义
- 输入与输出:算法的输入包括一个分类器 f f f及其损失函数 J J J、一个良性样本 x x x及其真实标签 y t r u e y^{true} ytrue、标签集合 C C C、迭代次数 T T T、扰动阈值 ϵ \epsilon ϵ、虚拟步长 α \alpha α以及辅助标签的数量 n a u x n_{aux} naux。输出为生成的对抗样本 x a d v x^{adv} xadv。
- 中间变量定义:在算法执行过程中, x t a d v x_{t}^{adv} xtadv表示第 t t t次迭代时的对抗样本,初始化为原始样本 x x x; x t + 1 a d v x_{t+1}^{adv} xt+1adv表示第 t + 1 t + 1 t+1次迭代时更新后的对抗样本; x t a d v t m p x_{t}^{adv tmp} xtadvtmp是在计算过程中临时存储的中间变量; y + t r u e y_{+}^{true} y+true表示根据真实标签的损失梯度上升方向更新对抗样本; y − a u x y_{-}^{aux} y−aux表示根据辅助标签的损失梯度下降方向更新对抗样本; C a u x C_{aux} Caux表示从标签集合 C C C中随机选择的辅助标签集合,且不包含真实标签 y t r u e y^{true} ytrue。
算法流程
- 初始化:
- 将对抗样本 x a d v x^{adv} xadv初始化为原始良性样本 x x x,即 x 0 a d v ← x x_{0}^{adv} \leftarrow x x0adv←x,并设置迭代次数 t ← 0 t \leftarrow 0 t←0。
- 迭代更新:在每次迭代中执行以下操作。
- 计算基于真实标签的梯度更新:根据当前对抗样本 x t a d v x_{t}^{adv} xtadv和真实标签 y t r u e y^{true} ytrue计算损失函数的梯度 ∇ x J ( x t a d v , y t r u e ) \nabla_{x} J(x_{t}^{adv}, y^{true}) ∇xJ(xtadv,ytrue),然后按照虚拟步长 α \alpha α在梯度方向上更新对抗样本,得到临时变量 x t a d v t m p x_{t}^{adv tmp} xtadvtmp,计算公式为 x t a d v t m p ← x t a d v + α ⋅ s i g n ( ∇ x J ( x t a d v , y t r u e ) ) x_{t}^{adv tmp} \leftarrow x_{t}^{adv}+\alpha \cdot sign(\nabla_{x} J(x_{t}^{adv}, y^{true})) xtadvtmp←xtadv+α⋅sign(∇xJ(xtadv,ytrue))。
- 计算基于辅助标签的梯度更新:从标签集合 C C C中随机选择 n a u x n_{aux} naux个不包含真实标签 y t r u e y^{true} ytrue的辅助标签,组成集合 C a u x C_{aux} Caux。对于每个辅助标签 y a u x ∈ C a u x y^{aux} \in C_{aux} yaux∈Caux,根据当前对抗样本 x t a d v x_{t}^{adv} xtadv和辅助标签 y a u x y^{aux} yaux计算损失函数的梯度 ∇ x J ( x t a d v , y a u x ) \nabla_{x} J(x_{t}^{adv}, y^{aux}) ∇xJ(xtadv,yaux),然后按照虚拟步长 α \alpha α在梯度的相反方向上更新临时变量 x t a d v t m p x_{t}^{adv tmp} xtadvtmp,计算公式为 x t a d v t m p ← x t a d v t m p − α ⋅ s i g n ( ∇ x J ( x t a d v , y a u x ) ) x_{t}^{adv tmp} \leftarrow x_{t}^{adv tmp}-\alpha \cdot sign(\nabla_{x} J(x_{t}^{adv}, y^{aux})) xtadvtmp←xtadvtmp−α⋅sign(∇xJ(xtadv,yaux))。
- 更新对抗样本:将经过上述两步更新后的临时变量 x t a d v t m p x_{t}^{adv tmp} xtadvtmp赋值给下一次迭代的对抗样本 x t + 1 a d v x_{t + 1}^{adv} xt+1adv,即 x t + 1 a d v ← x t a d v t m p x_{t + 1}^{adv} \leftarrow x_{t}^{adv tmp} xt+1adv←xtadvtmp。
- 迭代次数增加:将迭代次数 t t t增加1,即 t ← t + 1 t \leftarrow t + 1 t←t+1。
- 裁剪最终对抗样本:当迭代次数达到设定的最大值 T T T时,对最终的对抗样本 x T a d v x_{T}^{adv} xTadv进行裁剪操作,使其满足扰动阈值 ϵ \epsilon ϵ的限制,得到最终的对抗样本 x a d v x^{adv} xadv,计算公式为 x a d v ← C l i p x , ϵ { x T a d v } x^{adv} \leftarrow Clip_{x,\epsilon}\{x_{T}^{adv}\} xadv←Clipx,ϵ{xTadv}。
VAI-FGSM代码实现
VAI-FGSM算法实现
import torch
import torch.nn as nn
def VA_I_FGSM(model, criterion, original_images, labels, epsilon, num_iterations=10, num_aux_labels=3):
"""
VA-I-FGSM (Virtual Step and Auxiliary Gradients Iterative Fast Gradient Sign Method)
参数:
- model: 要攻击的模型
- criterion: 损失函数
- original_images: 原始图像
- labels: 原始图像的标签
- epsilon: 最大扰动幅度
- num_iterations: 迭代次数
- virtual_step_size: 虚拟步长
- num_aux_labels: 辅助标签数量
"""
# 虚拟步长
alpha = epsilon / num_iterations
# 复制原始图像作为初始的对抗样本
ori_perturbed_images = original_images.clone().detach().requires_grad_(True)
perturbed_images = original_images.clone().detach().requires_grad_(True)
for _ in range(num_iterations):
outputs = model(ori_perturbed_images)
loss = criterion(outputs, labels)
model.zero_grad()
loss.backward()
# 计算基于真实标签的梯度
main_grad = ori_perturbed_images.grad.data.sign()
perturbed_images = perturbed_images + alpha * main_grad
# 迭代num_aux_labels次数
for _ in range(num_aux_labels):
# 每次迭代中,都随机生成张量aux_labels,其与labels尺寸相同
aux_labels = torch.randint(low=0, high=10, size=labels.size(), device=original_images.device)
# 检查并替换与真实标签相同的辅助标签
mask = aux_labels == labels
while mask.any():
aux_labels[mask] = torch.randint(low=0, high=10, size=(mask.sum(),), device=original_images.device)
mask = aux_labels == labels
# 计算辅助标签的损失
outputs = model(ori_perturbed_images)
aux_loss = criterion(outputs, aux_labels)
model.zero_grad()
aux_loss.backward()
aux_grad = ori_perturbed_images.grad.data.sign()
perturbed_images = perturbed_images - alpha * aux_grad
ori_perturbed_images = ori_perturbed_images.detach().requires_grad_(True)
ori_perturbed_images = ori_perturbed_images.detach().requires_grad_(True)
# 确保对抗样本在epsilon范围内
perturbed_images = torch.clamp(perturbed_images, original_images - epsilon, original_images + epsilon)
return perturbed_images
攻击效果
代码汇总
vaifgsm.py
import torch
import torch.nn as nn
def VA_I_FGSM(model, criterion, original_images, labels, epsilon, num_iterations=10, num_aux_labels=3):
"""
VA-I-FGSM (Virtual Step and Auxiliary Gradients Iterative Fast Gradient Sign Method)
参数:
- model: 要攻击的模型
- criterion: 损失函数
- original_images: 原始图像
- labels: 原始图像的标签
- epsilon: 最大扰动幅度
- num_iterations: 迭代次数
- virtual_step_size: 虚拟步长
- num_aux_labels: 辅助标签数量
"""
# 虚拟步长
alpha = epsilon / num_iterations
# 复制原始图像作为初始的对抗样本
ori_perturbed_images = original_images.clone().detach().requires_grad_(True)
perturbed_images = original_images.clone().detach().requires_grad_(True)
for _ in range(num_iterations):
outputs = model(ori_perturbed_images)
loss = criterion(outputs, labels)
model.zero_grad()
loss.backward()
# 计算基于真实标签的梯度
main_grad = ori_perturbed_images.grad.data.sign()
perturbed_images = perturbed_images + alpha * main_grad
# 迭代num_aux_labels次数
for _ in range(num_aux_labels):
# 每次迭代中,都随机生成张量aux_labels,其与labels尺寸相同
aux_labels = torch.randint(low=0, high=10, size=labels.size(), device=original_images.device)
# 检查并替换与真实标签相同的辅助标签
mask = aux_labels == labels
while mask.any():
aux_labels[mask] = torch.randint(low=0, high=10, size=(mask.sum(),), device=original_images.device)
mask = aux_labels == labels
# 计算辅助标签的损失
outputs = model(ori_perturbed_images)
aux_loss = criterion(outputs, aux_labels)
model.zero_grad()
aux_loss.backward()
aux_grad = ori_perturbed_images.grad.data.sign()
perturbed_images = perturbed_images - alpha * aux_grad
ori_perturbed_images = ori_perturbed_images.detach().requires_grad_(True)
ori_perturbed_images = ori_perturbed_images.detach().requires_grad_(True)
# 确保对抗样本在epsilon范围内
perturbed_images = torch.clamp(perturbed_images, original_images - epsilon, original_images + epsilon)
return perturbed_images
train.py
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from models import ResNet18
# 数据预处理
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))
])
# 加载Cifar10训练集和测试集
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=False, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=False, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=2)
# 定义设备(GPU或CPU)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# 初始化模型
model = ResNet18(num_classes=10)
model.to(device)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
if __name__ == "__main__":
# 训练模型
for epoch in range(10): # 可以根据实际情况调整训练轮数
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
inputs, labels = data[0].to(device), data[1].to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 100 == 99:
print(f'Epoch {epoch + 1}, Batch {i + 1}: Loss = {running_loss / 100}')
running_loss = 0.0
torch.save(model.state_dict(), f'weights/epoch_{epoch + 1}.pth')
print('Finished Training')
advtest.py
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from models import *
from attacks import *
import ssl
import os
from PIL import Image
import matplotlib.pyplot as plt
ssl._create_default_https_context = ssl._create_unverified_context
# 定义数据预处理操作
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.491, 0.482, 0.446), (0.247, 0.243, 0.261))])
# 加载CIFAR10测试集
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=False, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=128,
shuffle=False, num_workers=2)
# 定义设备(GPU优先,若可用)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = ResNet18(num_classes=10).to(device)
criterion = nn.CrossEntropyLoss()
# 加载模型权重
weights_path = "weights/epoch_10.pth"
model.load_state_dict(torch.load(weights_path, map_location=device))
if __name__ == "__main__":
# 在测试集上进行FGSM攻击并评估准确率
model.eval() # 设置为评估模式
correct = 0
total = 0
epsilon = 16 / 255 # 可以调整扰动强度
for data in testloader:
original_images, labels = data[0].to(device), data[1].to(device)
original_images.requires_grad = True
attack_name = 'VA-I-FGSM'
if attack_name == 'FGSM':
perturbed_images = FGSM(model, criterion, original_images, labels, epsilon)
elif attack_name == 'BIM':
perturbed_images = BIM(model, criterion, original_images, labels, epsilon)
elif attack_name == 'MI-FGSM':
perturbed_images = MI_FGSM(model, criterion, original_images, labels, epsilon)
elif attack_name == 'NI-FGSM':
perturbed_images = NI_FGSM(model, criterion, original_images, labels, epsilon)
elif attack_name == 'PI-FGSM':
perturbed_images = PI_FGSM(model, criterion, original_images, labels, epsilon)
elif attack_name == 'VMI-FGSM':
perturbed_images = VMI_FGSM(model, criterion, original_images, labels, epsilon)
elif attack_name == 'VNI-FGSM':
perturbed_images = VNI_FGSM(model, criterion, original_images, labels, epsilon)
elif attack_name == 'EMI-FGSM':
perturbed_images = EMI_FGSM(model, criterion, original_images, labels, epsilon)
elif attack_name == 'AI-FGTM':
perturbed_images = AI_FGTM(model, criterion, original_images, labels, epsilon)
elif attack_name == 'I-FGSSM':
perturbed_images = I_FGSSM(model, criterion, original_images, labels, epsilon)
elif attack_name == 'SMI-FGRM':
perturbed_images = SMI_FGRM(model, criterion, original_images, labels, epsilon)
elif attack_name == 'VA-I-FGSM':
perturbed_images = VA_I_FGSM(model, criterion, original_images, labels, epsilon)
perturbed_outputs = model(perturbed_images)
_, predicted = torch.max(perturbed_outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = 100 * correct / total
# Attack Success Rate
ASR = 100 - accuracy
print(f'Load ResNet Model Weight from {weights_path}')
print(f'epsilon: {epsilon:.4f}')
print(f'ASR of {attack_name} : {ASR :.2f}%')