pycharm使用 FGSM 生成对抗性示例
时间: 2023-10-22 12:22:14 浏览: 83
pytorch_FGSM_对抗样本
5星 · 资源好评率100%
FGSM是一种常见的生成对抗性样本攻击方法,它可以在不改变原始图像的情况下,通过添加一些扰动来欺骗训练好的分类器。在PyCharm中使用FGSM生成对抗性示例,可以按照以下步骤进行:
1. 导入必要的Python库和模块:
```
import torch
import torchvision
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
```
2. 定义一个用于训练分类器的函数:
```
def train(model, device, train_loader, optimizer, criterion, epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
if batch_idx % 10 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
```
3. 定义一个用于测试分类器的函数:
```
def test(model, device, test_loader, criterion):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
test_loss += criterion(output, target).item()
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
```
4. 定义一个用于生成对抗性示例的函数:
```
def fgsm_attack(image, epsilon, data_grad):
sign_data_grad = data_grad.sign()
perturbed_image = image + epsilon * sign_data_grad
perturbed_image = torch.clamp(perturbed_image, 0, 1)
return perturbed_image
```
5. 定义一个用于运行模型的函数:
```
def run_model():
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using device:", device)
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST('./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST('./data', train=False, download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=1000, shuffle=True)
model = nn.Sequential(
nn.Conv2d(1, 20, 5, 1),
nn.ReLU(),
nn.MaxPool2d(2, 2),
nn.Conv2d(20, 50, 5, 1),
nn.ReLU(),
nn.MaxPool2d(2, 2),
nn.Flatten(),
nn.Linear(4 * 4 * 50, 500),
nn.ReLU(),
nn.Linear(500, 10),
).to(device)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
criterion = nn.CrossEntropyLoss()
for epoch in range(1, 11):
train(model, device, train_loader, optimizer, criterion, epoch)
test(model, device, test_loader, criterion)
epsilon = 0.1
for data, target in test_loader:
data, target = data.to(device), target.to(device)
data.requires_grad = True
output = model(data)
loss = criterion(output, target)
model.zero_grad()
loss.backward()
data_grad = data.grad.data
perturbed_data = fgsm_attack(data, epsilon, data_grad)
output = model(perturbed_data)
print(output.argmax(dim=1, keepdim=True).flatten())
break
```
6. 最后,运行上述函数:
```
run_model()
```
这将会训练一个简单的卷积神经网络模型来分类手写数字,并使用FGSM方法生成对抗性示例。可以通过调整epsilon的值来改变扰动的大小,以及通过在test_loader中迭代来生成多个示例。
阅读全文