Pytorch | 利用VMI-FGSM针对CIFAR10上的ResNet分类器进行对抗攻击
- CIFAR数据集
- VMI-FGSM介绍
- 核心思想
- 梯度方差定义
- 算法流程
- VMI-FGSM代码实现
- VMI-FGSM算法实现
- 攻击效果
- 代码汇总
- vmifgsm.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分类器进行攻击.
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个不同的类别,这些类别都是现实世界中常见的物体,具有一定的代表性。
下面是一些示例样本:
VMI-FGSM介绍
VMI-FGSM(Variance Tuning Momentum Iterative Fast Gradient Sign Method)基于方差调整的对抗攻击算法,用于增强对抗样本的迁移性,从而提高对黑盒模型的攻击成功率。以下是对这种算法的详细介绍:
核心思想
在每次迭代计算梯度时,不仅考虑当前梯度方向,还结合前一次迭代数据点邻域内的梯度方差来调整当前梯度,以此稳定更新方向,避免陷入局部最优解,从而提高对抗样本在不同模型间的迁移能力。
梯度方差定义
对于给定的分类器 f f f、参数 θ \theta θ、损失函数 J ( x , y ; θ ) J(x,y;\theta) J(x,y;θ)、任意图像 x ∈ X x\in X x∈X 以及邻域上界 ϵ \epsilon ϵ,梯度方差 V ϵ ′ g ( x ) V_{\epsilon'}^{g}(x) Vϵ′g(x) 定义为邻域内梯度期望与当前点梯度之差,即:
V ϵ ′ g ( x ) = E ∥ x ′ − x ∥ p < ϵ ′ [ ∇ x ′ J ( x ′ , y ; θ ) ] − ∇ x J ( x , y ; θ ) V_{\epsilon'}^{g}(x)=\mathbb{E}_{\left\| x'-x\right\| _{p}<\epsilon'}\left[\nabla_{x'} J\left(x', y; \theta\right)\right]-\nabla_{x} J(x, y; \theta) Vϵ′g(x)=E∥x′−x∥p<ϵ′[∇x′J(x′,y;θ)]−∇xJ(x,y;θ)。
在实际计算中,由于输入空间连续性无法直接计算期望,通过在邻域内采样 N N N 个样本来近似计算, V ( x ) = 1 N ∑ i = 1 N ∇ x i J ( x i , y ; θ ) − ∇ x J ( x , y ; θ ) V(x)=\frac{1}{N} \sum_{i=1}^{N} \nabla_{x^{i}} J\left(x^{i}, y; \theta\right)-\nabla_{x} J(x, y; \theta) V(x)=N1∑i=1N∇xiJ(xi,y;θ)−∇xJ(x,y;θ),
其中: x i = x + r i x^{i}=x+r_{i} xi=x+ri, r i ∼ U [ − ( β ⋅ ϵ ) d , ( β ⋅ ϵ ) d ] r_{i} \sim U[-(\beta \cdot \epsilon)^{d},(\beta \cdot \epsilon)^{d}] ri∼U[−(β⋅ϵ)d,(β⋅ϵ)d], U [ a d , b d ] U[a^{d},b^{d}] U[ad,bd] 表示 d d d维均匀分布。
算法流程
- 输入: 分类器 f f f、损失函数 J J J、原始样本 x x x 及其真实标签 y y y、扰动幅度 ϵ \epsilon ϵ、迭代次数 T T T、衰减因子 μ \mu μ、邻域因子 β \beta β 和用于方差调整的样本数 N N N。
- 初始化: 设置步长 α = ϵ T \alpha=\frac{\epsilon}{T} α=Tϵ,动量 g 0 = 0 g_{0}=0 g0=0,梯度方差 v 0 = 0 v_{0}=0 v0=0,初始对抗样本 x 0 a d v = x x_{0}^{adv}=x x0adv=x。
- 迭代过程: 在每次迭代 t t t中,计算当前对抗样本 x t a d v x_{t}^{adv} xtadv 的梯度 g ^ t + 1 = ∇ x t a d v J ( x t a d v , y ; θ ) \hat{g}_{t + 1}=\nabla_{x_{t}^{adv}} J(x_{t}^{adv}, y; \theta) g^t+1=∇xtadvJ(xtadv,y;θ),然后通过方差调整更新动量 g t + 1 = μ ⋅ g t + g ^ t + 1 + v t ∥ g ^ t + 1 + v t ∥ 1 g_{t + 1}=\mu \cdot g_{t}+\frac{\hat{g}_{t + 1}+v_{t}}{\left\|\hat{g}_{t + 1}+v_{t}\right\|_{1}} gt+1=μ⋅gt+∥g^t+1+vt∥1g^t+1+vt,接着更新梯度方差 v t + 1 = V ( x t a d v ) v_{t + 1}=V(x_{t}^{adv}) vt+1=V(xtadv),最后根据动量方向更新对抗样本 x t + 1 a d v = x t a d v + α ⋅ s i g n ( g t + 1 ) x_{t + 1}^{adv}=x_{t}^{adv}+\alpha \cdot sign(g_{t + 1}) xt+1adv=xtadv+α⋅sign(gt+1)。
- 输出: 经过 T T T 次迭代后得到的对抗样本 x a d v = x T a d v x^{adv}=x_{T}^{adv} xadv=xTadv。
VMI-FGSM代码实现
VMI-FGSM算法实现
当设置 N = 0 N=0 N=0 时,VMI-FGSM 退化为 MI-FGSM.
import torch
import torch.nn as nndef VMI_FGSM(model, criterion, original_images, labels, epsilon, num_iterations=10, decay=1, beta=1.5, N=20):"""VMI-FGSM (Variance Tuning Momentum Iterative Fast Gradient Sign Method)参数:- model: 要攻击的模型- criterion: 损失函数- original_images: 原始图像- labels: 原始图像的标签- epsilon: 最大扰动幅度- num_iterations: 迭代次数- decay: 动量衰减因子- beta: 邻域因子,用于确定计算梯度方差的邻域范围- N: 在邻域内采样的样本数量,用于近似计算梯度方差"""# alpha每次迭代步长alpha = epsilon / num_iterations# 复制原始图像作为初始的对抗样本perturbed_images = original_images.clone().detach().requires_grad_(True)momentum = torch.zeros_like(original_images).detach().to(original_images.device)# 初始化梯度方差为0variance = torch.zeros_like(original_images).detach().to(original_images.device)for _ in range(num_iterations):outputs = model(perturbed_images)loss = criterion(outputs, labels)model.zero_grad()loss.backward()data_grad = perturbed_images.grad.data# 计算邻域内的梯度方差variance = variance_tuning(model, criterion, perturbed_images, labels, epsilon, beta, N, data_grad)# 更新动量,结合梯度方差momentum = decay * momentum + (data_grad + variance) / torch.sum(torch.abs(data_grad + variance), dim=(1, 2, 3), keepdim=True)# 计算带动量和方差调整的符号梯度sign_data_grad = momentum.sign()# 更新对抗样本perturbed_images = perturbed_images + alpha * sign_data_gradperturbed_images = torch.clamp(perturbed_images, original_images - epsilon, original_images + epsilon)perturbed_images = perturbed_images.detach().requires_grad_(True)return perturbed_imagesdef variance_tuning(model, criterion, perturbed_images, labels, epsilon, beta, N, data_grad):"""计算给定图像的梯度方差参数:- original_images: 原始图像- perturbed_images: 当前的对抗样本- model: 要攻击的模型- criterion: 损失函数- beta: 邻域因子,用于确定计算梯度方差的邻域范围- N: 在邻域内采样的样本数量,用于近似计算梯度方差"""epsilon_prime = beta * epsilonvariance = torch.zeros_like(perturbed_images).detach().to(perturbed_images.device)for _ in range(N):# 在邻域内随机采样扰动random_perturbation = torch.randn_like(perturbed_images).uniform_(-epsilon_prime, epsilon_prime)# 应用扰动得到邻域内的样本neighbor_images = perturbed_images + random_perturbationneighbor_images = torch.clamp(neighbor_images, 0, 1)neighbor_images = neighbor_images.detach().requires_grad_(True)# 计算邻域样本的梯度outputs = model(neighbor_images)loss = criterion(outputs, labels)model.zero_grad()loss.backward()neighbor_grad = neighbor_images.grad.data# 累加梯度差variance += neighbor_grad - data_grad# 平均梯度差得到梯度方差variance /= Nreturn variance
攻击效果
代码汇总
vmifgsm.py
import torch
import torch.nn as nndef VMI_FGSM(model, criterion, original_images, labels, epsilon, num_iterations=10, decay=1, beta=1.5, N=20):"""VMI-FGSM (Variance Tuning Momentum Iterative Fast Gradient Sign Method)参数:- model: 要攻击的模型- criterion: 损失函数- original_images: 原始图像- labels: 原始图像的标签- epsilon: 最大扰动幅度- num_iterations: 迭代次数- decay: 动量衰减因子- beta: 邻域因子,用于确定计算梯度方差的邻域范围- N: 在邻域内采样的样本数量,用于近似计算梯度方差"""# alpha每次迭代步长alpha = epsilon / num_iterations# 复制原始图像作为初始的对抗样本perturbed_images = original_images.clone().detach().requires_grad_(True)momentum = torch.zeros_like(original_images).detach().to(original_images.device)# 初始化梯度方差为0variance = torch.zeros_like(original_images).detach().to(original_images.device)for _ in range(num_iterations):outputs = model(perturbed_images)loss = criterion(outputs, labels)model.zero_grad()loss.backward()data_grad = perturbed_images.grad.data# 计算邻域内的梯度方差variance = variance_tuning(model, criterion, perturbed_images, labels, epsilon, beta, N, data_grad)# 更新动量,结合梯度方差momentum = decay * momentum + (data_grad + variance) / torch.sum(torch.abs(data_grad + variance), dim=(1, 2, 3), keepdim=True)# 计算带动量和方差调整的符号梯度sign_data_grad = momentum.sign()# 更新对抗样本perturbed_images = perturbed_images + alpha * sign_data_gradperturbed_images = torch.clamp(perturbed_images, original_images - epsilon, original_images + epsilon)perturbed_images = perturbed_images.detach().requires_grad_(True)return perturbed_imagesdef variance_tuning(model, criterion, perturbed_images, labels, epsilon, beta, N, data_grad):"""计算给定图像的梯度方差参数:- original_images: 原始图像- perturbed_images: 当前的对抗样本- model: 要攻击的模型- criterion: 损失函数- beta: 邻域因子,用于确定计算梯度方差的邻域范围- N: 在邻域内采样的样本数量,用于近似计算梯度方差"""epsilon_prime = beta * epsilonvariance = torch.zeros_like(perturbed_images).detach().to(perturbed_images.device)for _ in range(N):# 在邻域内随机采样扰动random_perturbation = torch.randn_like(perturbed_images).uniform_(-epsilon_prime, epsilon_prime)# 应用扰动得到邻域内的样本neighbor_images = perturbed_images + random_perturbationneighbor_images = torch.clamp(neighbor_images, 0, 1)neighbor_images = neighbor_images.detach().requires_grad_(True)# 计算邻域样本的梯度outputs = model(neighbor_images)loss = criterion(outputs, labels)model.zero_grad()loss.backward()neighbor_grad = neighbor_images.grad.data# 累加梯度差variance += neighbor_grad - data_grad# 平均梯度差得到梯度方差variance /= Nreturn variance
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.0for 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.0torch.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 pltssl._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 = 0total = 0epsilon = 16 / 255 # 可以调整扰动强度for data in testloader:original_images, labels = data[0].to(device), data[1].to(device)original_images.requires_grad = Trueattack_name = 'VMI-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)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 RateASR = 100 - accuracyprint(f'Load ResNet Model Weight from {weights_path}')print(f'epsilon: {epsilon:.4f}')print(f'ASR of {attack_name} : {ASR :.2f}%')