Pytorch | 利用I-FGSSM针对CIFAR10上的ResNet分类器进行对抗攻击
- CIFAR数据集
- I-FGSSM介绍
- I-FGSSM代码实现
- I-FGSSM算法实现
- 攻击效果
- 代码汇总
- ifgssm.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 ( I − F G S 2 M I-FGS^2M I−FGS2M) 对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个不同的类别,这些类别都是现实世界中常见的物体,具有一定的代表性。
下面是一些示例样本:
I-FGSSM介绍
I-FGSSM(基于迭代快速梯度符号法的改进方法)是一种用于提升对抗攻击效果的方法,它是在FGSM算法的基础上进行改进,以解决Sign Method(SM)在转移攻击中存在的梯度估计不准确的问题,从而提高对抗样本的转移性。以下是I-FGSSM的详细算法流程:
- 初始化
- 输入:交叉熵损失函数 J J J、迭代次数 T T T、 ℓ ∞ \ell_{\infty} ℓ∞ 约束 ϵ \epsilon ϵ、干净图像 x x x(归一化到 [ − 1 , 1 ] [-1, 1] [−1,1])及其真实标签 y y y、目标标签 y ∗ y^* y∗、阶梯数量 K K K( K ≥ 2 K\geq2 K≥2)。
- 输出:对抗样本 x ∗ x^* x∗。
- 初始化对抗样本 x 0 ∗ = x x_0^* = x x0∗=x,计算步长 α = ϵ / T \alpha = \epsilon / T α=ϵ/T,初始化阶梯权重 W W W 为0,初始化百分位数 p = 100 / K p = 100 / K p=100/K。
- 迭代计算
- 对于 t = 0 t = 0 t=0 到 T − 1 T - 1 T−1 进行迭代:
- 计算模型在 x t ∗ x_t^* xt∗ 处关于输入的梯度 G t = ∇ x t ∗ J ( x t ∗ , y ∗ ) G_t = \nabla_{x_t^*} J(x_t^*, y^*) Gt=∇xt∗J(xt∗,y∗)。
- 对于 k = 0 k = 0 k=0 到 K − 1 K - 1 K−1,计算 ∣ G t ∣ |G_t| ∣Gt∣ 的第 p p p 百分位数 g t p g_t^p gtp,其中 p p p 的范围从 100 / K 100 / K 100/K 到100,百分位数间隔 τ = 100 / K \tau = 100 / K τ=100/K。
- 根据 g t p g_t^p gtp 分配阶梯权重 W t W_t Wt: W t = { τ 100 , g t 0 ≤ ∣ G t i , j ∣ ≤ g t τ 3 τ 100 , g t τ < ∣ G t i , j ∣ ≤ g t 2 τ ⋮ ( 2 k + 1 ) τ 100 , g t p − τ < ∣ G t i , j ∣ ≤ g t p ⋮ ( 2 K − 1 ) τ 100 , g t 100 − τ < ∣ G t i , j ∣ ≤ g t 100 W_t = \begin{cases} \frac{\tau}{100}, & g_t^0 \leq |G_t^{i,j}| \leq g_t^{\tau} \\ \frac{3\tau}{100}, & g_t^{\tau} < |G_t^{i,j}| \leq g_t^{2\tau} \\ \vdots \\ \frac{(2k + 1)\tau}{100}, & g_t^{p - \tau} < |G_t^{i,j}| \leq g_t^p \\ \vdots \\ \frac{(2K - 1)\tau}{100}, & g_t^{100 - \tau} < |G_t^{i,j}| \leq g_t^{100} \end{cases} Wt=⎩ ⎨ ⎧100τ,1003τ,⋮100(2k+1)τ,⋮100(2K−1)τ,gt0≤∣Gti,j∣≤gtτgtτ<∣Gti,j∣≤gt2τgtp−τ<∣Gti,j∣≤gtpgt100−τ<∣Gti,j∣≤gt100
其中 k k k 范围从0到 K − 1 K - 1 K−1,且 k = p / τ − 1 k = p / \tau - 1 k=p/τ−1, W t W_t Wt 的值范围在 [ 1 / K , 2 − 1 / K ] ⊆ [ 0 , 2 ] [1 / K, 2 - 1 / K] \subseteq [0, 2] [1/K,2−1/K]⊆[0,2]。 - 更新对抗样本 x t + 1 ∗ = c l i p x , ϵ { x t ∗ + α ⋅ s i g n ( G t ) ⊙ W t } x_{t + 1}^* = clip_{x,\epsilon}\{x_t^* + \alpha \cdot sign(G_t) \odot W_t\} xt+1∗=clipx,ϵ{xt∗+α⋅sign(Gt)⊙Wt},其中 c l i p x , ϵ ( ⋅ ) clip_{x,\epsilon}(\cdot) clipx,ϵ(⋅) 用于将对抗样本限制在 x x x 的 ϵ \epsilon ϵ球内, ⊙ \odot ⊙ 表示Hadamard乘积。然后将 x t + 1 ∗ x_{t + 1}^* xt+1∗ 再次裁剪到 [ − 1 , 1 ] [-1, 1] [−1,1] 范围内。
- 对于 t = 0 t = 0 t=0 到 T − 1 T - 1 T−1 进行迭代:
- 返回结果:返回最终的对抗样本 x ∗ = x T ∗ x^* = x_T^* x∗=xT∗。
在每次迭代中,I-FGSSM通过计算梯度并根据梯度值分配阶梯权重,对图像进行扰动更新,从而生成更具转移性的对抗样本。这种方法能够更有效地利用梯度信息,使对抗样本更接近全局最优攻击区域,提高了在白盒和黑盒攻击场景下的成功率。
I-FGSSM代码实现
I-FGSSM算法实现
import torch
import torch.nn as nndef I_FGSSM(model, criterion, original_images, labels, epsilon, num_iterations=10, staircase_num=64):"""I-FGSSM (Iterative Fast Gradient Staircase Sign Method)参数:model: 要攻击的模型criterion: 损失函数original_images: 原始图像labels: 原始图像的标签epsilon: 最大扰动幅度num_iterations: 迭代次数staircase_num: 阶梯数量(默认为64)"""# 计算步长alphaalpha = epsilon / num_iterationsperturbed_images = original_images.clone().detach().requires_grad_(True)for _ in range(num_iterations):# 计算损失outputs = model(perturbed_images)loss = criterion(outputs, labels)model.zero_grad()# 计算梯度loss.backward()gradients = perturbed_images.grad# 计算梯度绝对值的百分位数percentile_interval = 100 / staircase_numpercentiles = []for p in [percentile_interval * i for i in range(1, staircase_num + 1)]:percentiles.append(torch.quantile(gradients.abs().view(-1), p / 100))# 根据百分位数分配阶梯权重weights = torch.zeros_like(gradients)for i in range(staircase_num):lower_bound = percentiles[i - 1] if i > 0 else 0upper_bound = percentiles[i]mask = (lower_bound <= gradients.abs()) & (gradients.abs() <= upper_bound)weights[mask] = (2 * i + 1) * percentile_interval / 100# 更新对抗样本perturbation = alpha * gradients.sign() * weightsperturbed_images = perturbed_images + perturbationperturbed_images = torch.clamp(perturbed_images, original_images - epsilon, original_images + epsilon)perturbed_images = perturbed_images.detach().requires_grad_(True)return perturbed_images
攻击效果
代码汇总
ifgssm.py
import torch
import torch.nn as nndef I_FGSSM(model, criterion, original_images, labels, epsilon, num_iterations=10, staircase_num=64):"""I-FGSSM (Iterative Fast Gradient Staircase Sign Method)参数:model: 要攻击的模型criterion: 损失函数original_images: 原始图像labels: 原始图像的标签epsilon: 最大扰动幅度num_iterations: 迭代次数staircase_num: 阶梯数量(默认为64)"""# 计算步长alphaalpha = epsilon / num_iterationsperturbed_images = original_images.clone().detach().requires_grad_(True)for _ in range(num_iterations):# 计算损失outputs = model(perturbed_images)loss = criterion(outputs, labels)model.zero_grad()# 计算梯度loss.backward()gradients = perturbed_images.grad# 计算梯度绝对值的百分位数percentile_interval = 100 / staircase_numpercentiles = []for p in [percentile_interval * i for i in range(1, staircase_num + 1)]:percentiles.append(torch.quantile(gradients.abs().view(-1), p / 100))# 根据百分位数分配阶梯权重weights = torch.zeros_like(gradients)for i in range(staircase_num):lower_bound = percentiles[i - 1] if i > 0 else 0upper_bound = percentiles[i]mask = (lower_bound <= gradients.abs()) & (gradients.abs() <= upper_bound)weights[mask] = (2 * i + 1) * percentile_interval / 100# 更新对抗样本perturbation = alpha * gradients.sign() * weightsperturbed_images = perturbed_images + perturbationperturbed_images = torch.clamp(perturbed_images, original_images - epsilon, original_images + epsilon)perturbed_images = perturbed_images.detach().requires_grad_(True)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.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 = 'I-FGSSM'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)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}%')