bethgelab / foolbox

A Python toolbox to create adversarial examples that fool neural networks in PyTorch, TensorFlow, and JAX
https://foolbox.jonasrauber.de
MIT License
2.79k stars 426 forks source link

Problem with creating attacks/ adversarial instances using pytorch (in example code) #241

Closed filbart closed 6 years ago

filbart commented 6 years ago

Hello, I've run into a similiar issue as #194 while trying to run example code. I am recieving a following error while creating the attack ( adversarial = attack(image, label) )

RuntimeError: Expected object of type torch.LongTensor but found type torch.IntTensor for argument #2 'target'

I've checked and updated versions of foolbox, torch, torchvision, numpy and scipy. Also tried rewriting the example slightly (code below), still getting the same error.

import foolbox
import torch
import torchvision
import torchvision.models as models
import numpy as np

device = torch.device('cpu')

resnet18 = models.resnet18(pretrained=True).to(device).eval()

mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))
std = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))
fmodel = foolbox.models.PyTorchModel(
    resnet18, bounds=(0, 1), num_classes=1000, preprocessing=(mean, std), device=device)

image, label = foolbox.utils.imagenet_example(data_format='channels_first')
image = image / 255.  # because our model expects values in [0, 1]

print('label', label)
print('predicted class', np.argmax(fmodel.predictions(image)))

attack = foolbox.attacks.FGSM(fmodel)
adversarial = attack(image, label)

print('adversarial class', np.argmax(fmodel.predictions(adversarial)))
samuelemarro commented 6 years ago

Converting standard types to Torch tensors is a bit messy and often leads to bugs such as this one. As a workaround, replace attack(image, label) with attack(image, np.array(label, dtype=np.int64)).

filbart commented 6 years ago

Works like a charm, thanks!

wielandbrendel commented 6 years ago

Thanks for reporting and thanks for the work-around! I fixed this problem in master.