def main(): """ Advbox demo which demonstrate how to use advbox. """ TOTAL_NUM = 2 pretrained_model = "./mnist-pytorch/net.pth" loss_func = torch.nn.CrossEntropyLoss() test_loader = torch.utils.data.DataLoader(datasets.MNIST( './mnist-pytorch/data', train=False, download=True, transform=transforms.Compose([ transforms.ToTensor(), ])), batch_size=1, shuffle=False) # Define what device we are using logging.info("CUDA Available: {}".format(torch.cuda.is_available())) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Initialize the network model = Net().to(device) # Load the pretrained model model.load_state_dict(torch.load(pretrained_model, map_location='cpu')) # Set the model in evaluation mode. In this case this is for the Dropout layers model.eval() # advbox demo m = PytorchModel(model, loss_func, (0, 1), channel_axis=1) attack = FGSM(m) attack_config = { "epsilons": 0.2, "epsilon_steps": 1, "epsilons_max": 0.2, "norm_ord": 1, "steps": 10 } # use test data to generate adversarial examples total_count = 0 fooling_count = 0 for i, data in enumerate(test_loader): inputs, labels = data #inputs, labels = inputs.to(device), labels.to(device) inputs, labels = inputs.numpy(), labels.numpy() #inputs.requires_grad = True #print(inputs.shape) total_count += 1 adversary = Adversary(inputs, labels[0]) # FGSM non-targeted attack adversary = attack(adversary, **attack_config) if adversary.is_successful(): fooling_count += 1 print( 'attack success, original_label=%d, adversarial_label=%d, count=%d' % (labels, adversary.adversarial_label, total_count)) else: print('attack failed, original_label=%d, count=%d' % (labels, total_count)) if total_count >= TOTAL_NUM: print( "[TEST_DATASET]: fooling_count=%d, total_count=%d, fooling_rate=%f" % (fooling_count, total_count, float(fooling_count) / total_count)) break print("fgsm attack done")
def main(image_path): # Define what device we are using logging.info("CUDA Available: {}".format(torch.cuda.is_available())) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") orig = cv2.imread(image_path)[..., ::-1] orig = cv2.resize(orig, (224, 224)) img = orig.copy().astype(np.float32) mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] img /= 255.0 img = (img - mean) / std img = img.transpose(2, 0, 1) img = Variable( torch.from_numpy(img).to(device).float().unsqueeze(0)).cpu().numpy() # Initialize the network #Alexnet model = models.alexnet(pretrained=True).to(device).eval() #model = models.resnet18(pretrained=True).to(device).eval() #print(model) #设置为不保存梯度值 自然也无法修改 for param in model.parameters(): #print(param) #print(param.requires_grad) param.requires_grad = False #loss_func=nn.CrossEntropyLoss() # advbox demo m = PytorchModel(model, None, (-1, 1), channel_axis=1) attack = FGSMT(m) #attack = FGSM(m) # 静态epsilons attack_config = {"epsilons": 0.2, "epsilon_steps": 1, "steps": 100} inputs = img #labels=388 labels = None print(inputs.shape) adversary = Adversary(inputs, labels) #adversary = Adversary(inputs, 388) tlabel = 538 adversary.set_target(is_targeted_attack=True, target_label=tlabel) adversary = attack(adversary, **attack_config) if adversary.is_successful(): print('attack success, adversarial_label=%d' % (adversary.adversarial_label)) adv = adversary.adversarial_example[0] adv = adv.transpose(1, 2, 0) adv = (adv * std) + mean adv = adv * 255.0 adv = adv[..., ::-1] # RGB to BGR adv = np.clip(adv, 0, 255).astype(np.uint8) cv2.imwrite('img_adv.png', adv) else: print('attack failed') print("fgsm attack done")
def main(): # file_list = open('file_list.txt', 'r') # Lines = file_list.readlines() # # for line in Lines: # save_folder = 'data/' + line.split(line.strip().split('/',2)[2],1)[0] # if not os.path.exists(save_folder): # makedirs(save_folder) # # source = 'project/Materials/data/' + line.strip() # dest = 'data/' + line.strip() # copyfile(source, dest) normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) data_loader = torch.utils.data.DataLoader(datasets.ImageFolder( 'data/clean_images', transforms.Compose([ transforms.Resize(128), transforms.CenterCrop(128), transforms.ToTensor(), normalize, ])), batch_size=64) model = load_model('project/Materials/model/model.pt', 'cpu') correct = 0 for i, data in enumerate(data_loader): inputs, labels = data output = model(inputs) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(labels.view_as(pred)).sum().item() print('\n Accuracy Before : {}/{} ({:.0f}%)\n'.format( correct, len(data_loader.dataset), 100. * correct / len(data_loader.dataset))) loss_func = torch.nn.CrossEntropyLoss() m = PytorchModel(model, None, (-2.0665, 2.64), channel_axis=0, nb_classes=4) device = torch.device("cpu") for data, target in data_loader: data, target = data.to(device), target.to(device) for k in range(data.shape[0]): adv_img = np.copy(data[k, :, :]) original_label = target[k] h = 128 w = 128 min_ = -2.0665 max_ = 2.64 max_pixels = 1000 pixels = np.random.permutation(h * w) pixels = pixels[:max_pixels] print(k) for i, pixel in enumerate(pixels): x = pixel % w y = pixel // w location = [x, y] print("Attack x={0} y={1}".format(x, y)) channel_axis = 0 location.insert(channel_axis, slice(None)) location = tuple(location) # 图像经过预处理 取值为整数 通常范围为0-1 cnt = 0 for value in np.linspace(min_, max_, num=256): # logger.info("value in [min_={0}, max_={1},step num=256]".format(min_, max_)) perturbed = np.copy(adv_img) # 针对图像的每个信道的点[x,y]同时进行修改 perturbed[location] = value f = model(torch.from_numpy(perturbed).unsqueeze(0)) adv_label = np.argmax(f) cnt += 1 # if adversary.try_accept_the_example(adv_img, adv_label): if adv_label != original_label: print(str(cnt) + " found") break