Pytorch | 利用MIG针对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分类器进行对抗攻击
Pytorch | 利用VA-I-FGSM针对CIFAR10上的ResNet分类器进行对抗攻击
Pytorch | 利用PC-I-FGSM针对CIFAR10上的ResNet分类器进行对抗攻击
Pytorch | 利用IE-FGSM针对CIFAR10上的ResNet分类器进行对抗攻击
Pytorch | 利用GRA针对CIFAR10上的ResNet分类器进行对抗攻击
Pytorch | 利用GNP针对CIFAR10上的ResNet分类器进行对抗攻击
本篇文章我们使用Pytorch实现MIG对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个不同的类别,这些类别都是现实世界中常见的物体,具有一定的代表性。
下面是一些示例样本:
MIG介绍
MIG(Momentum Integrated Gradients)算法是一种用于对抗攻击的算法,旨在提高对抗样本在不同模型(尤其是视觉变换器ViTs和卷积神经网络CNNs)之间的可迁移性。以下是MIG算法的详细流程:
算法流程
-
输入与初始化:
- 输入 :源白盒模型 f f f、原始干净图像 x x x及其标签 y y y。
- 参数设置 :扰动预算 ϵ \epsilon ϵ、迭代次数 T T T、动量因子 μ \mu μ和基线图像 b b b(通常为黑色图像)。
- 初始化 :初始累积积分梯度 g 0 = 0 g_0 = 0 g0=0;令 x 0 = x x_0 = x x0=x,步长 α = ϵ T \alpha = \frac{\epsilon}{T} α=Tϵ。
-
迭代过程(从t=0到T-1):
- 计算积分梯度 :计算模型输出关于当前输入 x t − 1 x_{t - 1} xt−1的积分梯度 Δ t = I G ( f , x t − 1 , b ) \Delta_t = IG(f, x_{t - 1}, b) Δt=IG(f,xt−1,b)。这里通过近似计算从基线图像 b b b到输入图像 x t − 1 x_{t - 1} xt−1直线路径上各点梯度的积分来得到积分梯度,近似公式为 I G i ( f , x , b ) ≈ ( x i − b i ) × ∑ k = 1 s ∂ f ( b + k s × ( x − b ) ) ∂ x i × 1 s IG_i(f, x, b) \approx (x_i - b_i) × \sum_{k = 1}^{s} \frac{\partial f(b + \frac{k}{s}×(x - b))}{\partial x_i} × \frac{1}{s} IGi(f,x,b)≈(xi−bi)×∑k=1s∂xi∂f(b+sk×(x−b))×s1,其中 s s s为近似阶数(本文设为20)。
- 动量更新累积梯度 :通过动量迭代方法更新累积梯度 g t g_t gt,公式为 g t = μ ∗ g t − 1 + Δ t ∥ Δ t ∥ 1 g_t = \mu * g_{t - 1} + \frac{\Delta_t}{\|\Delta_t\|1} gt=μ∗gt−1+∥Δt∥1Δt,其中 g t − 1 g{t - 1} gt−1是上一次迭代的累积积分梯度, Δ t \Delta_t Δt是当前迭代的积分梯度,并在相加前通过 L 1 L_1 L1范数进行归一化。
- 更新输入图像 :根据累积梯度的符号更新输入图像 x t = C l i p ϵ { x t − 1 + α ⋅ s i g n ( g t ) } x_t = Clip_{\epsilon}\{x_{t - 1} + \alpha · sign(g_t)\} xt=Clipϵ{xt−1+α⋅sign(gt)},其中 C l i p ϵ Clip_{\epsilon} Clipϵ表示将更新后的图像裁剪到原始图像 x x x的 ϵ \epsilon ϵ邻域内,以确保扰动在可接受范围内。
-
输出:
- 经过 T T T次迭代后,得到最终的对抗样本 x a d v = x T x_{adv} = x_T xadv=xT。
MIG代码实现
MIG算法实现
python
import torch
import torch.nn as nn
def MIG(model, original_images, labels, epsilon, num_iterations=25, decay=1, baseline_images=None):
"""
MIG (Momentum Integrated Gradients)算法
参数:
- model: 要攻击的模型
- original_images: 原始图像
- labels: 原始图像的标签
- epsilon: 最大扰动幅度
- num_iterations: 迭代次数
- decay: 动量衰减因子
- baseline_images: 基线图像,默认为黑色图像(全零张量)
"""
if baseline_images is None:
baseline_images = torch.zeros_like(original_images)
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):
# 计算积分梯度
integrated_gradients = calculate_integrated_gradients(model, perturbed_images, baseline_images)
# 更新动量
momentum = decay * momentum + integrated_gradients / torch.sum(torch.abs(integrated_gradients), dim=(1, 2, 3), keepdim=True)
sign_data_grad = momentum.sign()
# 更新对抗样本
perturbed_images = perturbed_images + alpha * sign_data_grad
perturbed_images = torch.clamp(perturbed_images, original_images - epsilon, original_images + epsilon)
perturbed_images = perturbed_images.detach().requires_grad_(True)
return perturbed_images
def calculate_integrated_gradients(model, input_images, baseline_images, num_steps=2):
"""
计算积分梯度
参数:
- model: 模型
- input_images: 输入图像
- baseline_images: 基线图像
- num_steps: 计算积分梯度的步数
"""
integrated_gradients = torch.zeros_like(input_images)
for step in range(num_steps):
step_size = 1.0 / num_steps
interpolated_images = baseline_images + step_size * (input_images - baseline_images)
interpolated_images = interpolated_images.clone().detach().requires_grad_(True)
outputs = model(interpolated_images)
model.zero_grad()
outputs.backward(torch.ones_like(outputs))
gradients = interpolated_images.grad.data
integrated_gradients += gradients * (input_images - baseline_images) * step_size
return integrated_gradients
攻击效果
这里展示的是 num_steps=2
的结果,效果较差,实际中可以调整为 num_steps=20
.
代码汇总
mig.py
python
import torch
import torch.nn as nn
def MIG(model, original_images, labels, epsilon, num_iterations=25, decay=1, baseline_images=None):
"""
MIG (Momentum Integrated Gradients)算法
参数:
- model: 要攻击的模型
- original_images: 原始图像
- labels: 原始图像的标签
- epsilon: 最大扰动幅度
- num_iterations: 迭代次数
- decay: 动量衰减因子
- baseline_images: 基线图像,默认为黑色图像(全零张量)
"""
if baseline_images is None:
baseline_images = torch.zeros_like(original_images)
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):
# 计算积分梯度
integrated_gradients = calculate_integrated_gradients(model, perturbed_images, baseline_images)
# 更新动量
momentum = decay * momentum + integrated_gradients / torch.sum(torch.abs(integrated_gradients), dim=(1, 2, 3), keepdim=True)
sign_data_grad = momentum.sign()
# 更新对抗样本
perturbed_images = perturbed_images + alpha * sign_data_grad
perturbed_images = torch.clamp(perturbed_images, original_images - epsilon, original_images + epsilon)
perturbed_images = perturbed_images.detach().requires_grad_(True)
return perturbed_images
def calculate_integrated_gradients(model, input_images, baseline_images, num_steps=2):
"""
计算积分梯度
参数:
- model: 模型
- input_images: 输入图像
- baseline_images: 基线图像
- num_steps: 计算积分梯度的步数
"""
integrated_gradients = torch.zeros_like(input_images)
for step in range(num_steps):
step_size = 1.0 / num_steps
interpolated_images = baseline_images + step_size * (input_images - baseline_images)
interpolated_images = interpolated_images.clone().detach().requires_grad_(True)
outputs = model(interpolated_images)
model.zero_grad()
outputs.backward(torch.ones_like(outputs))
gradients = interpolated_images.grad.data
integrated_gradients += gradients * (input_images - baseline_images) * step_size
return integrated_gradients
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 = 'MIG'
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)
elif attack_name == 'PC-I-FGSM':
perturbed_images = PC_I_FGSM(model, criterion, original_images, labels, epsilon)
elif attack_name == 'IE-FGSM':
perturbed_images = IE_FGSM(model, criterion, original_images, labels, epsilon)
elif attack_name == 'GRA':
perturbed_images = GRA(model, criterion, original_images, labels, epsilon)
elif attack_name == 'GNP':
perturbed_images = GNP(model, criterion, original_images, labels, epsilon)
elif attack_name == 'MIG':
perturbed_images = MIG(model, 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}%')