Pytorch | 利用I-FGSSM针对CIFAR10上的ResNet分类器进行对抗攻击
之前已经针对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分类器进行攻击.
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个不同的类别,这些类别都是现实世界中常见的物体,具有一定的代表性。
下面是一些示例样本:
SMI-FGRM介绍
SMI-FGRM(Sampling-based Momentum Iterative Fast Gradient Rescaling Method)是一种基于采样的动量迭代快速梯度重缩放方法,用于提升对抗攻击的可迁移性。它在传统的MI-FGSM算法基础上,引入了数据重缩放和深度优先采样策略,以更准确地近似梯度方向,从而提高攻击效果。
SMI-FGRM算法流程
- 初始化
- 设置步长 α = ϵ / T \alpha=\epsilon/T α=ϵ/T,其中 ϵ \epsilon ϵ 是最大扰动, T T T 是迭代次数。初始化对抗样本 x 0 a d v = x x^{adv}_0 = x x0adv=x,动量 g 0 = 0 g_0 = 0 g0=0。
- 迭代过程( t = 0 t = 0 t=0 到 T − 1 T - 1 T−1)
- 计算采样梯度 g ^ t + 1 \hat{g}_{t + 1} g^t+1
- 根据深度优先采样方法(DFSM),在输入空间中对当前点的邻居进行采样,计算采样点和原始图像的平均梯度。具体公式为 g ^ t = 1 N + 1 ∑ i = 0 N ∇ J ( x t i , y ; θ ) \hat{g}{t}=\frac{1}{N + 1} \sum{i = 0}^{N} \nabla J\left(x_{t}^{i}, y ; \theta\right) g^t=N+11∑i=0N∇J(xti,y;θ),其中 x t 0 = x x_{t}^{0}=x xt0=x, ξ i ∼ U [ − ( β ⋅ ϵ ) d , ( β ⋅ ϵ ) d ] \xi_{i} \sim U[-(\beta \cdot \epsilon)^{d},(\beta \cdot \epsilon)^{d}] ξi∼U[−(β⋅ϵ)d,(β⋅ϵ)d], N N N 是采样数量, β \beta β 是确定采样范围的超参数, ∇ J ( x t i , y ; θ ) \nabla J\left(x_{t}^{i}, y ; \theta\right) ∇J(xti,y;θ) 是损失函数 J J J 关于输入 x t i x_{t}^{i} xti 的梯度。
- 更新动量 g t + 1 g_{t + 1} gt+1
- 使用计算得到的采样梯度 g ^ t + 1 \hat{g}{t + 1} g^t+1 更新动量 g t + 1 g{t + 1} gt+1,公式为 g t + 1 = μ g t + g ^ t + 1 ∥ g ^ t + 1 ∥ 1 g_{t + 1}=\mu g_{t}+\frac{\hat{g}{t + 1}}{\left\|\hat{g}{t + 1}\right\|_{1}} gt+1=μgt+∥g^t+1∥1g^t+1,其中 μ \mu μ 是衰减因子。
- 更新对抗样本 x t + 1 a d v x^{adv}_{t + 1} xt+1adv
- 通过快速梯度重缩放方法(FGRM)计算梯度缩放后的扰动,更新对抗样本。具体为 x t + 1 a d v = x t a d v + α ⋅ r e s c a l e ( g t + 1 ) x^{adv}{t + 1}=x^{adv}{t}+\alpha \cdot rescale(g_{t + 1}) xt+1adv=xtadv+α⋅rescale(gt+1),其中 r e s c a l e ( g ) rescale(g) rescale(g) 是梯度重缩放函数,定义为 r e s c a l e ( g ) = c ∗ s i g n ( g ) ⊙ f ( n o r m ( l o g 2 ∣ g ∣ ) ) rescale(g)=c * sign(g) \odot f\left(norm\left(log _{2}|g|\right)\right) rescale(g)=c∗sign(g)⊙f(norm(log2∣g∣)), n o r m ( x ) = x − m e a n ( x ) s t d ( x ) norm(x)=\frac{x - mean(x)}{std(x)} norm(x)=std(x)x−mean(x), f ( x ) = σ = 1 1 + e − x f(x)=\sigma=\frac{1}{1 + e^{-x}} f(x)=σ=1+e−x1, c c c 是重缩放因子。
- 计算采样梯度 g ^ t + 1 \hat{g}_{t + 1} g^t+1
- 返回结果
- 迭代结束后,返回最终的对抗样本 x a d v = x T a d v x^{adv}=x^{adv}_T xadv=xTadv。
SMI-FGRM代码实现
当 sampling_num=0
时,SMI-FGRM退化为MI-FGRM.
SMI-FGRM算法实现
python
import torch
import torch.nn as nn
def SMI_FGRM(model, criterion, original_images, labels, epsilon, num_iterations=10, decay=1, sampling_num=12, sampling_beta=1.5, rescale_c=2):
"""
SMI-FGRM (Sampling-based Momentum Iterative Fast Gradient Rescaling Method)
参数:
- model: 要攻击的模型
- criterion: 损失函数
- original_images: 原始图像
- labels: 原始图像的标签
- epsilon: 最大扰动幅度
- num_iterations: 迭代次数
- decay: 动量衰减因子
- sampling_num: 采样数量
- sampling_beta: 采样范围参数
- rescale_c: 重缩放因子
"""
alpha = epsilon / num_iterations
perturbed_images = original_images.clone().detach().requires_grad_(True)
momentum = torch.zeros_like(original_images).detach().to(original_images.device)
for _ in range(num_iterations):
# 深度优先采样
sampled_gradients = []
x_i = perturbed_images.clone()
for _ in range(sampling_num):
xi = x_i + torch.randn_like(x_i) * (sampling_beta * epsilon)
sampled_gradients.append(compute_gradient(model, criterion, xi, labels))
x_i = xi
sampled_gradients.append(compute_gradient(model, criterion, perturbed_images, labels))
g_hat = torch.mean(torch.stack(sampled_gradients), dim=0)
# 更新动量
momentum = decay * momentum + g_hat / torch.sum(torch.abs(g_hat), dim=(1, 2, 3), keepdim=True)
# 快速梯度重缩放
rescaled_gradient = rescale_gradient(momentum, rescale_c)
# 更新对抗样本
perturbed_images = perturbed_images + alpha * rescaled_gradient
perturbed_images = torch.clamp(perturbed_images, original_images - epsilon, original_images + epsilon)
perturbed_images = perturbed_images.detach().requires_grad_(True)
return perturbed_images
def rescale_gradient(g, c):
"""
梯度重缩放函数
参数:
- g: 梯度
- c: 重缩放因子
"""
normed_log_gradient = (torch.log2(torch.abs(g)) - torch.mean(torch.log2(torch.abs(g)), dim=(1, 2, 3), keepdim=True)) / torch.std(torch.log2(torch.abs(g)), dim=(1, 2, 3), keepdim=True)
sigmoid_applied = 1 / (1 + torch.exp(-normed_log_gradient))
return c * torch.sign(g) * sigmoid_applied
def compute_gradient(model, criterion, x, labels):
"""
计算梯度
参数:
- model: 模型
- criterion: 损失函数
- x: 输入图像
- labels: 标签
"""
x = x.clone().detach().requires_grad_(True)
outputs = model(x)
loss = criterion(outputs, labels)
model.zero_grad()
loss.backward()
return x.grad.data
攻击效果
代码汇总
smifgrm.py
python
import torch
import torch.nn as nn
def SMI_FGRM(model, criterion, original_images, labels, epsilon, num_iterations=10, decay=1, sampling_num=12, sampling_beta=1.5, rescale_c=2):
"""
SMI-FGRM (Sampling-based Momentum Iterative Fast Gradient Rescaling Method)
参数:
- model: 要攻击的模型
- criterion: 损失函数
- original_images: 原始图像
- labels: 原始图像的标签
- epsilon: 最大扰动幅度
- num_iterations: 迭代次数
- decay: 动量衰减因子
- sampling_num: 采样数量
- sampling_beta: 采样范围参数
- rescale_c: 重缩放因子
"""
alpha = epsilon / num_iterations
perturbed_images = original_images.clone().detach().requires_grad_(True)
momentum = torch.zeros_like(original_images).detach().to(original_images.device)
for _ in range(num_iterations):
# 深度优先采样
sampled_gradients = []
x_i = perturbed_images.clone()
for _ in range(sampling_num):
xi = x_i + torch.randn_like(x_i) * (sampling_beta * epsilon)
sampled_gradients.append(compute_gradient(model, criterion, xi, labels))
x_i = xi
sampled_gradients.append(compute_gradient(model, criterion, perturbed_images, labels))
g_hat = torch.mean(torch.stack(sampled_gradients), dim=0)
# 更新动量
momentum = decay * momentum + g_hat / torch.sum(torch.abs(g_hat), dim=(1, 2, 3), keepdim=True)
# 快速梯度重缩放
rescaled_gradient = rescale_gradient(momentum, rescale_c)
# 更新对抗样本
perturbed_images = perturbed_images + alpha * rescaled_gradient
perturbed_images = torch.clamp(perturbed_images, original_images - epsilon, original_images + epsilon)
perturbed_images = perturbed_images.detach().requires_grad_(True)
return perturbed_images
def rescale_gradient(g, c):
"""
梯度重缩放函数
参数:
- g: 梯度
- c: 重缩放因子
"""
normed_log_gradient = (torch.log2(torch.abs(g)) - torch.mean(torch.log2(torch.abs(g)), dim=(1, 2, 3), keepdim=True)) / torch.std(torch.log2(torch.abs(g)), dim=(1, 2, 3), keepdim=True)
sigmoid_applied = 1 / (1 + torch.exp(-normed_log_gradient))
return c * torch.sign(g) * sigmoid_applied
def compute_gradient(model, criterion, x, labels):
"""
计算梯度
参数:
- model: 模型
- criterion: 损失函数
- x: 输入图像
- labels: 标签
"""
x = x.clone().detach().requires_grad_(True)
outputs = model(x)
loss = criterion(outputs, labels)
model.zero_grad()
loss.backward()
return x.grad.data
train.py
python
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
python
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 = 'SMI-FGRM'
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)
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}%')