Example #1
0
def load_classifier(model, data):
    """
    Load ART PyTorch classifier from pytorch model
    :param model: pytorch model instance
    :param data: data class
    :return: ART classifier
    """
    # not used but mandatory for ART
    criterion = torch.nn.CrossEntropyLoss()
    optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
    classifier = PyTorchClassifier(
        model=model,
        clip_values=(data.min_pixel_value, data.max_pixel_value),
        loss=criterion,
        optimizer=optimizer,
        input_shape=tuple(data.trainset.data.shape[1:]),
        nb_classes=data.num_classes,
        device_type="gpu" if USE_CUDA else "cpu")
    classifier.set_learning_phase(False)
    return classifier
# Step 2a: Define the loss function and the optimizer

criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.01)

# Step 3: Create the ART classifier

classifier = PyTorchClassifier(
    model=model,
    clip_values=(-1, 1),
    loss=criterion,
    optimizer=optimizer,
    input_shape=(1, 28, 28),
    nb_classes=10,
)
classifier.set_learning_phase(False)

# Step 4: Evaluate the ART classifier on benign test examples

count = 0
ben_sum = 0
att_sum = 0
for i, (imgs, labels) in enumerate(testloader):
    predictions = classifier.predict(imgs)
    accuracy = np.sum(np.argmax(predictions, axis=1) == labels.numpy()) / 128
    #print("Accuracy on benign test examples: {}%".format(accuracy * 100))
    ben_sum += accuracy

    # Step 5: Generate adversarial test examples
    attack = FastGradientMethod(classifier=classifier)
    x_test_adv = attack.generate(x=imgs)