Beispiel #1
0
def run():
    torch.multiprocessing.freeze_support()

    use_cuda=True
    image_nc=1
    epochs = 60
    batch_size = 128
    BOX_MIN = 0
    BOX_MAX = 1

    # Define what device we are using
    print("CUDA Available: ",torch.cuda.is_available())
    device = torch.device("cuda" if (use_cuda and torch.cuda.is_available()) else "cpu")

    pretrained_model = "./MNIST_target_model.pth"
    targeted_model = MNIST_target_net().to(device)
    targeted_model.load_state_dict(torch.load(pretrained_model))
    targeted_model.eval()
    model_num_labels = 10

    # MNIST train dataset and dataloader declaration
    mnist_dataset = torchvision.datasets.MNIST('./dataset', train=True, transform=transforms.ToTensor(), download=True)
    dataloader = DataLoader(mnist_dataset, batch_size=batch_size, shuffle=True, num_workers=1)
    advGAN = AdvGAN_Attack(device,
                            targeted_model,
                            model_num_labels,
                            image_nc,
                            BOX_MIN,
                            BOX_MAX)

    advGAN.train(dataloader, epochs)   
Beispiel #2
0
if __name__ == "__main__":
    
    use_cuda=True
    image_nc=1
    batch_size = 128

    gen_input_nc = image_nc

    # Define what device we are using
    print("CUDA Available: ",torch.cuda.is_available())
    device = torch.device("cuda" if (use_cuda and torch.cuda.is_available()) else "cpu")

    # load the pretrained model
    pretrained_model = "./MNIST_target_model.pth"
    target_model = MNIST_target_net().to(device)
    target_model.load_state_dict(torch.load(pretrained_model))
    target_model.eval()

    # load the generator of adversarial examples
    pretrained_generator_path = './models/netG.pth.tar'
    pretrained_G = models.Generator(gen_input_nc, image_nc).to(device)
    pretrained_G.load_state_dict(torch.load(pretrained_generator_path))
    pretrained_G.eval()

    # test adversarial examples in MNIST training dataset
    mnist_dataset = torchvision.datasets.MNIST('./dataset', train=True, transform=transforms.ToTensor(), download=True)
    train_dataloader = DataLoader(mnist_dataset, batch_size=batch_size, shuffle=False, num_workers=1)
    num_correct = 0
    num_all = 0
    for i, data in enumerate(train_dataloader, 0):
def run():
    use_cuda = True
    image_nc = 1
    batch_size = 128

    gen_input_nc = image_nc

    # Define what device we are using
    print("CUDA Available: ", torch.cuda.is_available())
    device = torch.device("cuda" if (
        use_cuda and torch.cuda.is_available()) else "cpu")

    # load the pretrained model
    pretrained_model = "./MNIST_target_model_2.pth"
    target_model = MNIST_target_net().to(device)
    target_model.load_state_dict(torch.load(pretrained_model))
    target_model.eval()

    # load the generator of adversarial examples
    pretrained_generator_path = './models/netG_epoch_40.pth'
    pretrained_G = models.Generator(gen_input_nc, image_nc).to(device)
    pretrained_G.load_state_dict(torch.load(pretrained_generator_path))
    pretrained_G.eval()

    # test adversarial examples in MNIST training dataset
    mnist_dataset = torchvision.datasets.MNIST('./dataset',
                                               train=True,
                                               transform=transforms.ToTensor(),
                                               download=True)
    train_dataloader = DataLoader(mnist_dataset,
                                  batch_size=batch_size,
                                  shuffle=False,
                                  num_workers=1)
    num_correct = 0
    for i, data in enumerate(train_dataloader, 0):
        test_img, test_label = data
        test_img, test_label = test_img.to(device), test_label.to(device)
        perturbation = pretrained_G(test_img)
        perturbation = torch.clamp(perturbation, -0.3, 0.3)
        adv_img = perturbation + test_img
        adv_img = torch.clamp(adv_img, 0, 1)
        pred_lab = torch.argmax(target_model(adv_img), 1)
        num_correct += torch.sum(pred_lab == test_label, 0)

    print('MNIST training dataset:')
    print('num_correct: ', num_correct.item())
    print('accuracy of adv imgs in training set: %f\n' %
          (num_correct.item() / len(mnist_dataset)))

    # test adversarial examples in MNIST testing dataset
    mnist_dataset_test = torchvision.datasets.MNIST(
        './dataset',
        train=False,
        transform=transforms.ToTensor(),
        download=True)
    test_dataloader = DataLoader(mnist_dataset_test,
                                 batch_size=batch_size,
                                 shuffle=False,
                                 num_workers=1)
    num_correct = 0
    for i, data in enumerate(test_dataloader, 0):
        test_img, test_label = data
        test_img, test_label = test_img.to(device), test_label.to(device)
        perturbation = pretrained_G(test_img)
        perturbation = torch.clamp(perturbation, -0.3, 0.3)
        adv_img = perturbation + test_img
        adv_img = torch.clamp(adv_img, 0, 1)
        pred_lab = torch.argmax(target_model(adv_img), 1)
        num_correct += torch.sum(pred_lab == test_label, 0)

    print('num_correct: ', num_correct.item())
    print('accuracy of adv imgs in testing set: %f\n' %
          (num_correct.item() / len(mnist_dataset_test)))
Beispiel #4
0
    writer = SummaryWriter(log_base_dir)

else:
    writer = None

if not os.path.exists(models_path):
    os.makedirs(models_path)
if not os.path.exists(models_path + model_name):
    os.makedirs(models_path + model_name)

# Define what device we are using print("CUDA Available: ",torch.cuda.is_available())
device = torch.device("cuda" if (
    use_cuda and torch.cuda.is_available()) else "cpu")

pretrained_model = "./MNIST_target_model.pth"
targeted_model = MNIST_target_net().to(device)
targeted_model.load_state_dict(
    torch.load(pretrained_model, map_location=device))
targeted_model.eval()
model_num_labels = 10

# MNIST train dataset and dataloader declaration
mnist_dataset = torchvision.datasets.MNIST('./dataset',
                                           train=True,
                                           transform=transforms.ToTensor(),
                                           download=True)
dataloader = DataLoader(mnist_dataset,
                        batch_size=batch_size,
                        shuffle=True,
                        num_workers=1)
advGAN = AdvGAN_Attack(device, targeted_model, model_num_labels, image_nc,
    parser.add_argument('--data', default='./dataset/real_and_fake_face')
    parser.add_argument('--seed', default=0, type=int)
    parser.add_argument('--epsilon', default=0.3, type=float)
    args = parser.parse_args()
    for arg in vars(args):
        print(arg, getattr(args, arg))

    # Define what device we are using
    print("CUDA Available: ", torch.cuda.is_available())
    device = torch.device("cuda" if (use_cuda and torch.cuda.is_available()) else "cpu")

    mnist_dataset = torchvision.datasets.MNIST('./dataset', train=True, transform=transforms.ToTensor(), download=True)
    train_dataloader = DataLoader(mnist_dataset, batch_size=args.batch_size, shuffle=True, num_workers=1)

    # training the target model
    target_model = MNIST_target_net().to(device)
    target_model.train()
    opt_model = torch.optim.Adam(target_model.parameters(), lr=0.0001)
    epochs = args.epochs

    pgd = PGD(target_model, None, None, device, args.epsilon, 7, args.epsilon/4)
    for epoch in range(epochs):
        loss_epoch = 0
        if epoch == 20:
            opt_model = torch.optim.Adam(target_model.parameters(), lr=0.00001)

        num_corrects = 0
        adv_num_corrects = 0
        total = 0
        for i, data in enumerate(train_dataloader, 0):
            train_imgs, train_labels = data
    args = parser.parse_args()
    for arg in vars(args):
        print(arg, getattr(args, arg))

    model_name = name_maker(args)

    en_input_nc = image_nc
    # Define what device we are using
    print("CUDA Available: ", torch.cuda.is_available())
    device = torch.device("cuda" if (use_cuda and torch.cuda.is_available()) else "cpu")
    print()

    # load the pretrained model
    model_path = "./MNIST_target_model.pth"
    target_model = MNIST_target_net().to(device)
    target_model.load_state_dict(torch.load(model_path, map_location=device))
    if args.parameters_count:
        print('number of parameters(model):', parameters_count(target_model))
    target_model.eval()

    epoch = args.epoch

    # load encoder & generators
    E_path = models_path + model_name + 'E_epoch_{}.pth'.format(epoch)
    E = models.Encoder(en_input_nc).to(device)
    E.load_state_dict(torch.load(E_path, map_location=device))
    if args.parameters_count:
        print('number of parameters(E):', parameters_count(E))
    E.eval()