目前,我正在尝试使用MNIST示例对最不可能的类方法进行编码。但是,当num_steps> 1时,此代码将不会运行。我找不到重复多次的方法。
'''python
def ll_attack(model, criterion, images, alpha, epsilon, num_steps=2):
outputs = model(images)
idx = torch.min(outputs,1)[1]
idx = idx.detach_()
for i in range(num_steps):
ouputs = model(images)
model.zero_grad()
loss = criterion(outputs, idx).to(device)
loss.backward()
pertubed_images = images - alpha*images.grad.sign()
out = torch.clamp(pertubed_images, -epsilon, epsilon).detach_()
return out
correct = 0
total = 0
criterion = torch.nn.CrossEntropyLoss()
for images, labels in test_loader:
images=images.to(device)
labels=labels.to(device)
images.requires_grad =True
pertubed_images = ll_attack(new_net, criterion, images, alpha, epsilon)
labels = labels.to(device)
outputs = new_net(pertubed_images)
adv_pred = torch.max(outputs.data, 1)[1]
total += 64
correct += (adv_pred == labels).sum()
print('Accuracy:{}'.format(int(correct)/total))`
'''
RuntimeError:尝试第二次向后浏览图形,但缓冲区已被释放。第一次回叫时,请指定keep_graph = True。