当前位置: 首页 > news >正文

Pytorch | 利用FGSM针对CIFAR10上的ResNet分类器进行对抗攻击

Pytorch | 利用FGSM针对CIFAR10上的ResNet分类器进行对抗攻击

  • CIFAR数据集
  • FGSM介绍
  • FGSM代码实现
    • FGSM算法实现
    • 攻击效果
  • 代码汇总
    • fgsm.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实现快速梯度符号攻击Fast Gradient Sign Method, 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个不同的类别,这些类别都是现实世界中常见的物体,具有一定的代表性。

下面是一些示例样本:
在这里插入图片描述

FGSM介绍

FGSM(Fast Gradient Sign Method)算法是一种基于梯度的快速攻击算法,由Goodfellow等人在2015年提出,主要用于评估神经网络模型的鲁棒性。以下是对FGSM算法原理的详细介绍:

算法原理

  • FGSM算法的核心思想是利用神经网络的梯度信息来生成对抗样本。对于给定的输入样本,通过计算模型对该样本的损失函数关于输入的梯度,然后根据梯度的符号来确定扰动的方向,最后在该方向上添加一个小的扰动,得到对抗样本。
  • 具体而言,给定一个输入样本 x x x,其对应的真实标签为 y y y,模型的参数为 θ \theta θ,损失函数为 J ( θ , x , y ) J(\theta, x, y) J(θ,x,y)。首先计算损失函数 J J J 关于输入 x x x 的梯度 ∇ x J ( θ , x , y ) \nabla_x J(\theta, x, y) xJ(θ,x,y),然后根据梯度的符号确定扰动的方向 sign ( ∇ x J ( θ , x , y ) ) \text{sign}(\nabla_x J(\theta, x, y)) sign(xJ(θ,x,y)),最后生成对抗样本 x ′ = x + ϵ ⋅ sign ( ∇ x J ( θ , x , y ) ) x' = x + \epsilon \cdot \text{sign}(\nabla_x J(\theta, x, y)) x=x+ϵsign(xJ(θ,x,y)),其中 ϵ \epsilon ϵ 是一个很小的正数,用于控制扰动的大小。

FGSM代码实现

FGSM算法实现

import torch
import torch.nn as nndef FGSM(model, criterion, original_images, labels, epsilon):"""FGSM (Fast Gradient Sign Method)参数:- model: 要攻击的模型- criterion: 损失函数- original_images: 原始图像- labels: 原始图像的标签- epsilon: 扰动幅度"""perturbed_images = original_images.clone().detach().requires_grad_(True)outputs = model(perturbed_images)loss = criterion(outputs, labels)model.zero_grad()loss.backward()data_grad = perturbed_images.grad.datasign_data_grad = data_grad.sign()perturbed_images = perturbed_images + epsilon * sign_data_gradperturbed_images = torch.clamp(perturbed_images, original_images - epsilon, original_images + epsilon)return perturbed_images

攻击效果

在这里插入图片描述

代码汇总

fgsm.py

import torch
import torch.nn as nndef FGSM(model, criterion, original_images, labels, epsilon):"""FGSM (Fast Gradient Sign Method)参数:- model: 要攻击的模型- criterion: 损失函数- original_images: 原始图像- labels: 原始图像的标签- epsilon: 扰动幅度"""perturbed_images = original_images.clone().detach().requires_grad_(True)outputs = model(perturbed_images)loss = criterion(outputs, labels)model.zero_grad()loss.backward()data_grad = perturbed_images.grad.datasign_data_grad = data_grad.sign()perturbed_images = perturbed_images + epsilon * sign_data_gradperturbed_images = torch.clamp(perturbed_images, original_images - epsilon, original_images + epsilon)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 = 'FGSM'if attack_name == 'FGSM':perturbed_images = 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}')print(f'ASR of {attack_name} : {ASR}%')
http://www.lryc.cn/news/509436.html

相关文章:

  • 消息队列(二)消息队列的高可用原理
  • 大模型-使用Ollama+Dify在本地搭建一个专属于自己的聊天助手与知识库
  • 深入理解索引的最左匹配原则:底层逻辑解析
  • 微服务——数据管理与一致性
  • Docker之技术架构【八大架构演进之路】
  • CSP-X2024山东小学组T4:刷题
  • 【Windows指令】Windows常用快捷指令
  • NLP中的神经网络基础
  • 安全筑堤,效率破浪 | 统一运维管理平台下的免密登录应用解析
  • 初学elasticsearch
  • HTMLCSS:惊!3D 折叠按钮
  • SDK 指南
  • Web 应用项目开发全流程解析与实战经验分享
  • WPS中插入矩阵的方法
  • Python调用R语言中的程序包来执行回归树、随机森林、条件推断树和条件推断森林算法
  • uniapp input苹果中文键盘输入拼音直接切换输入焦点监听失效
  • 多智能体/多机器人网络中的图论法
  • 华为:数字化转型只有“起点”,没有“终点”
  • centos server系统新装后的网络配置
  • 【问题实录】服务器ping不通win11笔记本
  • WEB入门——文件上传漏洞
  • 公交车信息管理系统:构建智能城市交通的基石
  • jdk各个版本介绍
  • 分布式事务解决方案seata和MQ
  • 相机主要调试参数
  • 【C++11】可变模板参数
  • AAAI-2024 | 大语言模型赋能导航决策!NavGPT:基于大模型显式推理的视觉语言导航
  • @HeadFontStyle注解属性介绍
  • Exchange ProxyLogon 攻击链利用详解
  • C++小碗菜之五:关键字static