Pytorch | 使用PI-FGSM针对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实现PI-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个差别的类别,这些类别都是现实世界中常见的物体,具有肯定的代表性。
下面是一些示例样本:
https://i-blog.csdnimg.cn/direct/f7ce1c73867241b68b1ac074c84fb5e6.png
PI-FGSM介绍
PI-FGSM(Patch-wise Iterative Fast Gradient Sign Method)是一种针对主流正常练习和防御模型的黑盒攻击算法,旨在生成具有强转移性的对抗样本。该算法通过引入放大因子和投影核,以块(patch)为单元生成对抗噪声,从而进步对抗样本在差别模型间的转移性。
配景和动机
[*]DNN的对抗样本问题:深度神经网络(DNN)在取得巨大成绩的同时,面对着对抗样本的威胁。这些添加了人类难以察觉噪声的对抗样本,能够轻易愚弄先辈的DNN,使其做出不合理的推测,引发了对呆板学习算法安全性的担心。
[*]现有攻击方法的局限性:基于梯度的攻击方法是常见的攻击手段,其中迭代攻击在白盒设置下性能较好,但在黑盒设置中,由于攻击者无法获取目标模型信息,通常使用替换模型生成对抗样本,此时迭代攻击轻易陷入局部最优,转移性较差;单步攻击虽转移性较高,但性能欠佳。
[*]研究动机:基于DNN的特性,差别模型在识别时关注的判别区域差别,且判别区域通常具有聚集性。仅添加像素级噪声大概影响对抗样本的转移性,因此研究具有聚集性的扰动生成方法具有紧张意义。PI-FGSM旨在结合单步和迭代攻击的优点,在不牺牲替换模型性能的前提下进步转移性。
算法原理
[*]目标函数:PI-FGSM的目标是在满足 L ∞ L_{\infty} L∞ 范数束缚(即对抗扰动的最大幅度不超过 ϵ \epsilon ϵ)的条件下,最大化替换模型的交叉熵丧失,以生成能够成功诱骗目标模型的对抗样本。
[*]梯度盘算与放大:在每次迭代中,盘算当前对抗样本 x t a d v x_t^{adv} xtadv 关于丧失函数 J J J 的梯度 ∇ x J ( x t a d v , y ) \nabla_x J(x_t^{adv}, y) ∇xJ(xtadv,y),并将步长设置为 ϵ T × β \frac{\epsilon}{T} \times \beta Tϵ×β(其中 T T T 为总迭代次数, β \beta β 为放大因子),对梯度举行放大,以增加扰动的幅度,进步攻击的有效性。
[*]投影核与噪声重用:引入特殊的匀称投影核 W p W_p Wp,当累积放大噪声 a t a_t at 的 L ∞ L_{\infty} L∞ 范数超过阈值 ϵ \epsilon ϵ 时,通过投影核将超出部分的噪声投影到周围区域,生成“可行方向”的噪声,同时重用这部分噪声,增加噪声斑块的聚集程度,以更好地匹配图像中判别区域的聚集特性,进步对抗样本的转移性。
算法流程
[*]初始化累积放大噪声 a 0 a_0 a0 和裁剪噪声 C C C 为0,设置初始对抗样本 x 0 a d v = x c l e a n x_0^{adv}=x^{clean} x0adv=xclean。
[*]对于 t = 0 t = 0 t=0 到 T − 1 T - 1 T−1:
[*]盘算梯度 ∇ x J ( x t a d v , y ) \nabla_x J(x_t^{adv}, y) ∇xJ(xtadv,y)。
[*]更新累积放大噪声 a t + 1 = a t + β ⋅ ϵ T ⋅ s i g n ( ∇ x J ( x t a d v , y ) ) a_{t + 1}=a_t+\beta \cdot \frac{\epsilon}{T} \cdot sign(\nabla_x J(x_t^{adv}, y)) at+1=at+β⋅Tϵ⋅sign(∇xJ(xtadv,y))。
[*]如果 ∥ a t + 1 ∥ ∞ ≥ ϵ \|a_{t + 1}\|_{\infty} \geq \epsilon ∥at+1∥∞≥ϵ,则盘算裁剪噪声 C = c l i p ( ∣ a t + 1 ∣ − ϵ , 0 , ∞ ) ⋅ s i g n ( a t + 1 ) C = clip(|a_{t + 1}|-\epsilon, 0, \infty) \cdot sign(a_{t + 1}) C=clip(∣at+1∣−ϵ,0,∞)⋅sign(at+1),并更新 a t + 1 = a t + 1 + γ ⋅ s i g n ( W p ∗ C ) a_{t + 1}=a_{t + 1}+\gamma \cdot sign(W_p * C) at+1=at+1+γ⋅sign(Wp∗C)(其中 γ \gamma γ 为投影因子);否则 C = 0 C = 0 C=0。
[*]更新对抗样本 x t + 1 a d v = C l i p x c l e a n , ϵ { x t a d v + β ⋅ ϵ T ⋅ s i g n ( ∇ x J ( x t a d v , y ) ) + γ ⋅ s i g n ( W p ∗ C ) } x_{t + 1}^{adv}=Clip_{x^{clean}, \epsilon}\{x_t^{adv}+\beta \cdot \frac{\epsilon}{T} \cdot sign(\nabla_x J(x_t^{adv}, y))+\gamma \cdot sign(W_p * C)\} xt+1adv=Clipxclean,ϵ{xtadv+β⋅Tϵ⋅sign(∇xJ(xtadv,y))+γ⋅sign(Wp∗C)},并将其裁剪到 [ − 1 , 1 ] [-1, 1] [−1,1] 范围内。
[*]返回终极的对抗样本 x a d v = x T a d v x^{adv}=x_T^{adv} xadv=xTadv。
PI-FGSM代码实现
PI-FGSM算法实现
import torch
import torch.nn as nn
def PI_FGSM(model, criterion, original_images, labels, epsilon, beta=5, kernel_size=3, num_iterations=10):
"""
PI-FGSM (Patch-wise Iterative Fast Gradient Sign Method)
参数:
- model: 要攻击的模型
- criterion: 损失函数
- original_images: 原始图像
- labels: 原始图像的标签
- epsilon: 扰动幅度
- beta: 放大因子
- kernel_size: 投影核大小
- num_iterations: 迭代次数
返回:
- perturbed_image: 生成的对抗样本
"""
# gamma: 投影因子
gamma = epsilon / num_iterations * beta
# 初始化累积放大噪声和裁剪噪声
a = torch.zeros_like(original_images)
C = torch.zeros_like(original_images)
perturbed_images = original_images.clone().detach().requires_grad_(True)
# 定义投影核
Wp = torch.ones((kernel_size, kernel_size), dtype=torch.float32) / (kernel_size ** 2 - 1)
Wp = 0
Wp = Wp.expand(original_images.size(1), -1, -1).to(original_images.device)
Wp = Wp.unsqueeze(0)
for _ in range(num_iterations):
# 计算梯度
outputs = model(perturbed_images)
loss = criterion(outputs, labels)
model.zero_grad()
loss.backward()
data_grad = perturbed_images.grad.data
# 更新累积放大噪声
a = a + beta * (epsilon / num_iterations) * data_grad.sign()
# 裁剪噪声
if a.abs().max() >= epsilon:
C = (a.abs() - epsilon).clamp(0, float('inf')) * a.sign()
a = a + gamma * torch.nn.functional.conv2d(input=C, weight=Wp, stride=1, padding=kernel_size // 2)
# 更新对抗样本
perturbed_images = perturbed_images + beta * (epsilon / num_iterations) * data_grad.sign() + gamma * torch.nn.functional.conv2d(C, Wp, stride=1, padding=kernel_size // 2)
perturbed_images = torch.clamp(perturbed_images, original_images - epsilon, original_images + epsilon)
perturbed_images = perturbed_images.detach().requires_grad_(True)
return perturbed_images
攻击效果
https://i-blog.csdnimg.cn/direct/ca9905cb92b44db180e71929d91ae242.png
代码汇总
pifgsm.py
import torch
import torch.nn as nn
def PI_FGSM(model, criterion, original_images, labels, epsilon, beta=5, kernel_size=3, num_iterations=10):
"""
PI-FGSM (Patch-wise Iterative Fast Gradient Sign Method)
参数:
- model: 要攻击的模型
- criterion: 损失函数
- original_images: 原始图像
- labels: 原始图像的标签
- epsilon: 扰动幅度
- beta: 放大因子
- kernel_size: 投影核大小
- num_iterations: 迭代次数
返回:
- perturbed_image: 生成的对抗样本
"""
# gamma: 投影因子
gamma = epsilon / num_iterations * beta
# 初始化累积放大噪声和裁剪噪声
a = torch.zeros_like(original_images)
C = torch.zeros_like(original_images)
perturbed_images = original_images.clone().detach().requires_grad_(True)
# 定义投影核
Wp = torch.ones((kernel_size, kernel_size), dtype=torch.float32) / (kernel_size ** 2 - 1)
Wp = 0
Wp = Wp.expand(original_images.size(1), -1, -1).to(original_images.device)
Wp = Wp.unsqueeze(0)
for _ in range(num_iterations):
# 计算梯度
outputs = model(perturbed_images)
loss = criterion(outputs, labels)
model.zero_grad()
loss.backward()
data_grad = perturbed_images.grad.data
# 更新累积放大噪声
a = a + beta * (epsilon / num_iterations) * data_grad.sign()
# 裁剪噪声
if a.abs().max() >= epsilon:
C = (a.abs() - epsilon).clamp(0, float('inf')) * a.sign()
a = a + gamma * torch.nn.functional.conv2d(input=C, weight=Wp, stride=1, padding=kernel_size // 2)
# 更新对抗样本
perturbed_images = perturbed_images + beta * (epsilon / num_iterations) * data_grad.sign() + gamma * torch.nn.functional.conv2d(C, Wp, stride=1, padding=kernel_size // 2)
perturbed_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.0
for i, data in enumerate(trainloader, 0):
inputs, labels = data.to(device), data.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.to(device), data.to(device)
original_images.requires_grad = True
attack_name = 'PI-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)
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}%')
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]