Example #1
0
    def adv_data(self, data, output, ep = 0.3, num_steps = 40, perturb_step_size = 0.01):
        """
        Generate input(adversarial) data for training.
        """

        adversary = PGD(self.model)
        data_adv = adversary.generate(data, output.flatten(), epsilon = ep, num_steps = num_steps, step_size = perturb_step_size)
        output = self.model(data_adv)

        return data_adv, output
Example #2
0
def main(args):
    #Load Model.
    model = resnet.ResNet18().to('cuda')
    print("Load network")

    model.load_state_dict(
        torch.load("~/Documents/deeprobust_model/cifar_res18_120.pt"))
    model.eval()

    transform_val = transforms.Compose([
        transforms.ToTensor(),
    ])
    train_loader = torch.utils.data.DataLoader(datasets.MNIST(
        'deeprobust/image/defense/data',
        train=True,
        download=True,
        transform=transforms.Compose([transforms.ToTensor()])),
                                               batch_size=128,
                                               shuffle=True)
    test_loader = torch.utils.data.DataLoader(datasets.CIFAR10(
        'deeprobust/image/data',
        train=False,
        download=True,
        transform=transform_val),
                                              batch_size=128,
                                              shuffle=True)  #, **kwargs)

    normal_data, adv_data = None, None
    adversary = PGD(model)

    for x, y in train_loader:
        x, y = x.cuda(), t.cuda()
        y_pred = model(x)
        train_acc += accuracy(y_pred, y)
        x_adv = adversary.generate(x, y,
                                   **attack_params['PGD_CIFAR10']).float()
        y_adv = model(x_adv)
        adv_acc += accuracy(y_adv, y)
        train_n += y.size(0)

        x, x_adv = x.data, x_adv.data
        if normal_data is None:
            normal_data, adv_data = x, x_adv
        else:
            normal_data = torch.cat((normal_data, x))
            adv_data = torch.cat((adv_data, x_adv))

    print("Accuracy(normal) {:.6f}, Accuracy(FGSM) {:.6f}".format(
        train_acc / train_n * 100, adv_acc / train_n * 100))
    torch.save({"normal": normal_data, "adv": adv_data}, "data.tar")
    torch.save({"state_dict": model.state_dict()}, "cnn.tar")
Example #3
0
test_loader  = torch.utils.data.DataLoader(
                datasets.CIFAR10('deeprobust/image/data', train = False, download=True,
                transform = transform_val),
                batch_size = 1, shuffle=True) #, **kwargs)


classes = np.array(('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'))

xx, yy = next(iter(test_loader))
xx = xx.to('cuda').float()

predict0 = model(xx)
predict0= predict0.argmax(dim=1, keepdim=True)

adversary = PGD(model)
AdvExArray = adversary.generate(xx, yy, **attack_params['PGD_CIFAR10']).float()

predict1 = model(AdvExArray)
predict1= predict1.argmax(dim=1, keepdim=True)

print('====== RESULT =====')
print('true label',classes[yy.cpu()])
print('predict_orig',classes[predict0.cpu()])
print('predict_adv',classes[predict1.cpu()])

x_show = xx.cpu().numpy().swapaxes(1,3).swapaxes(1,2)[0]
# print('xx:', x_show)
plt.imshow(x_show, vmin = 0, vmax = 255)
plt.savefig('./adversary_examples/cifar_advexample_orig.png')
# print('x_show', x_show)
Example #4
0
    return parser.parse_args()


if __name__ == "__main__":
    # read arguments
    args = parameter_parser() # read argument and creat an argparse object

    # load model
    model = load_net(args.attack_model, args.file_name, args.path)

    print("===== START ATTACK =====")
    if(args.attack_method == "PGD"):
        from deeprobust.image.attack.pgd import PGD
        test_loader = generate_dataloader(args.dataset, args.batch_size)
        attack_method = PGD(model, args.device)
        utils.tab_printer(args)
        run_attack(attack_method, args.batch_size, args.batch_num, args.device, test_loader, epsilon = args.epsilon)

    elif(args.attack_method == "FGSM"):
        from deeprobust.image.attack.fgsm import FGSM
        test_loader = generate_dataloader(args.dataset, args.batch_size)
        attack_method = FGSM(model, args.device)
        utils.tab_printer(args)
        run_attack(attack_method, args.batch_size, args.batch_num, args.device, test_loader, epsilon = args.epsilon)

    elif(args.attack_method == "LBFGS"):
        from deeprobust.image.attack.lbfgs import LBFGS
        try:
            if (args.batch_size >1):
                raise ValueError("batch_size shouldn't be larger than 1.")