50次pgd攻击下生成mnist数据集的对抗样本,并将对抗样本转化为npy文件
时间: 2023-05-25 12:02:57 浏览: 135
用MNIST数据形成训练样本集
3星 · 编辑精心推荐
我们先定义PGD攻击的函数:
```python
import torch
import numpy as np
def pgd_attack(model, X, y, epsilon, alpha, num_iter):
"""PGD攻击(Projected Gradient Descent)"""
delta = torch.zeros_like(X, requires_grad=True)
for t in range(num_iter):
loss = torch.nn.CrossEntropyLoss()(model(X + delta), y)
loss.backward()
delta.data = (delta + alpha * delta.grad.detach().sign()).clamp(-epsilon, epsilon)
delta.grad.zero_()
return (X + delta).detach()
```
接下来,我们加载MNIST数据集和预训练模型:
```python
import torchvision
from torchvision import transforms
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = torch.load('mnist_cnn.pth').to(device)
```
然后我们可以用PGD攻击来生成对抗样本:
```python
epsilon = 0.3
alpha = 0.05
num_iter = 50
adv_samples = []
for i, (X, y) in enumerate(testset):
X, y = X.unsqueeze(0).to(device), y.unsqueeze(0).to(device)
adv = pgd_attack(model, X, y, epsilon, alpha, num_iter)
adv_samples.append(adv.cpu().numpy().squeeze())
if i % 1000 == 0:
print(f"Generated {i} adv samples")
adv_samples = np.asarray(adv_samples)
```
最后,我们将对抗样本保存为`npy`文件:
```python
np.save('adv_samples.npy', adv_samples)
```
完整代码如下:
阅读全文