p.requires_grad = False
            net.eval()
    else:
        for p in net.parameters():
            p.requires_grad = False
        net.eval()

    for epsilon in epsilon_set:
        train_dataset, val_dataset = utils.get_dataset(params)
        
        loader_test = torch.utils.data.DataLoader(val_dataset, 
            batch_size=256, shuffle=False)    
        #test(net, loader_test)

        if method == 'BayesWRM' or method == 'Bayes':
            adversary = FGSMAttack(model_list, epsilon, is_train=False)
            advacc = attack_over_test_data(model_list, adversary, param, loader_test)
        else:
            adversary = FGSMAttack(net, epsilon, is_train=False, advtraining=method)
            advacc = attack_over_test_data(net, adversary, param, loader_test)

        print('method',method,  'adv accuracy', advacc)
        advacc_set.append(advacc)

    df = pd.DataFrame(
        {'epsilon': list(epsilon_set),
         'advacc': advacc_set})

    df.to_csv(os.path.join('trafficsignwhitebox', method+'_FGSMwhitebox.csv'))

예제 #2
0
# Data loaders
test_dataset = datasets.MNIST(root='../data/',
                              train=False,
                              download=True,
                              transform=transforms.ToTensor())
loader_test = torch.utils.data.DataLoader(test_dataset,
                                          batch_size=param['test_batch_size'],
                                          shuffle=False)

# Setup model to be attacked
net = LeNet5()
net.load_state_dict(torch.load('models/adv_trained_lenet5.pkl'))

if torch.cuda.is_available():
    print('CUDA ensabled.')
    net.cuda()

for p in net.parameters():
    p.requires_grad = False
net.eval()

test(net, loader_test)

# Adversarial attack
adversary = FGSMAttack(net, param['epsilon'])
# adversary = LinfPGDAttack(net, random_start=False)

t0 = time()
attack_over_test_data(net, adversary, param, loader_test)
print('{}s eclipsed.'.format(time() - t0))
예제 #3
0
}
# Setup model to be attacked
net = models.resnet18(pretrained=False)
dim_in = net.fc.in_features
net.fc = nn.Linear(dim_in, 2)

num_epoch = 20
for epoch in range(num_epoch):
    print('{}/{}'.format(epoch + 1, num_epoch))
    print('-' * 10)
    net.load_state_dict(torch.load('model_save/' + str(epoch) + '.pth'))

    if torch.cuda.is_available():
        print('CUDA ensabled.')
        net.cuda()

    for p in net.parameters():
        p.requires_grad = False
    net.eval()

    test(net, dset_loaders['val'])

    # Adversarial attack
    adversary = FGSMAttack(net, param['epsilon'])
    # adversary = LinfPGDAttack(net, random_start=False)

    t0 = time()
    attack_over_test_data(net, adversary, param, dset_loaders['val'])
    print('{}s eclipsed.'.format(time() - t0))
    print('Finish attacking!')
    print()