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.73k stars 425 forks source link

Is it possible to set the default loss function of a foolbox model? #690

Closed John-Chin closed 2 years ago

John-Chin commented 2 years ago

When I create a fmodel (foolbox model) from a custom pytorch architecture, is there a way to set the default loss of the fmodel to MeanSquaredError?

In other words, is there a parameter for the loss function I can set when defining a fmodel so that whenever a built-in foolbox function (such as accuracy(fmodel, images, labels) or attack(fmodel, images, labels, epsilons=epsilons) ) is called, the function will automatically use the explicitly-defined loss?

Example of fmodel:

#Defining my model
class CNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 3)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = torch.flatten(x, 1)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        x = torch.mean(x)
        return x

model = CNN().eval()

# CREATING FMODEL
preprocessing = dict(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], axis=-3)
fmodel = PyTorchModel(model, bounds=(-1, 1),  preprocessing=preprocessing)
zimmerrol commented 2 years ago

Duplicate of #689. Closing this in favor of the original issue.