def main():
    log_folder = './results/plots/robustness/revision/luna/bn_adv/'
    makedirs(log_folder)
    # model = models.resnet50(pretrained=False)
    model = resnet50dsbn()
    num_classes = 1
    model.fc = nn.Linear(model.fc.in_features, num_classes)
    if torch.cuda.is_available():
        model = model.cuda()

    todo = 'test'
    if todo == 'test':  # set 'valid' fold for knee and luna dataset and set 'test' fold for CXR dataset
        eps = np.linspace(0, 0.01, num=21)
        for i in range(len(eps)):
            epsilon = eps[i]
            alpha = epsilon / 2
            attack = FastGradientSignUntargeted(model,
                                                epsilon,
                                                alpha,
                                                min_val=0,
                                                max_val=1,
                                                max_iters=10,
                                                _type='linf')
            trainer = Trainer(attack, log_folder)
            te_dataset = patd.PatchDataset(path_to_images='../luna16/IMGs/',
                                           fold='test',
                                           transform=tv.transforms.Compose([
                                               tv.transforms.Resize(64),
                                               tv.transforms.ToTensor()
                                           ]))
            te_loader = DataLoader(te_dataset,
                                   batch_size=1,
                                   shuffle=False,
                                   num_workers=1)
            checkpoint = torch.load(
                './checkpoint/luna/luna_linf_/checkpoint_best.pth')
            model.load_state_dict(checkpoint)
            trainer.test(model,
                         te_loader,
                         i,
                         adv_test=True,
                         use_pseudo_label=False,
                         if_AUC=True)
            # print("std acc: %.4f, adv_acc: %.4f" % (std_acc * 100, adv_acc * 100))
    else:
        raise NotImplementedError
示例#2
0
def main(args):

    save_folder = '%s_%s' % (args.dataset, args.affix)
    log_folder = os.path.join(args.log_root, save_folder)
    model_folder = os.path.join(args.model_root, save_folder)
    makedirs(log_folder)
    makedirs(model_folder)
    setattr(args, 'log_folder', log_folder)
    setattr(args, 'model_folder', model_folder)
    logger = create_logger(log_folder, args.todo, 'info')
    print_args(args, logger)

    # model = WideResNet(depth=34, num_classes=10, widen_factor=10, dropRate=0.0)
    model = models.resnet50(pretrained=args.pretrain)
    num_classes=8
    # model.classifier = nn.Linear(model.classifier.in_features, num_classes)
    model.fc = nn.Linear(model.fc.in_features, num_classes)

    attack = FastGradientSignUntargeted(model, 
                                        args.epsilon, 
                                        args.alpha, 
                                        min_val=0, 
                                        max_val=1, 
                                        max_iters=args.k, 
                                        _type=args.perturbation_type)

    if torch.cuda.is_available():
        model.cuda()
        # model = nn.DataParallel(model).cuda()

    trainer = Trainer(args, logger, attack)

    if args.todo == 'train':

        transform_train = tv.transforms.Compose([
                tv.transforms.Resize(256),
                tv.transforms.ToTensor(),
                tv.transforms.Lambda(lambda x: F.pad(x.unsqueeze(0),
                                   (4*6,4*6,4*6,4*6), mode='constant', value=0).squeeze()),
                tv.transforms.ToPILImage(),
                tv.transforms.RandomHorizontalFlip(),
                tv.transforms.ColorJitter(brightness=0.3, contrast=0.3, 
                                            saturation=0.3, hue=0.3),
                # tv.transforms.RandomRotation(25),
                tv.transforms.RandomAffine(25, translate=(0.2, 0.2), 
                                            scale=(0.8,1.2), shear=10),                            
                tv.transforms.RandomCrop(256),
                tv.transforms.ToTensor(),
                AddGaussianNoise(0.5, args.epsilon)
            ])
        tr_dataset = patd.PatchDataset(path_to_images=args.data_root,
                                        fold='train', 
                                        sample=args.subsample,
                                        transform=transform_train)
        tr_loader = DataLoader(tr_dataset, batch_size=args.batch_size, shuffle=True, num_workers=24)
        # evaluation during training
        transform_test = tv.transforms.Compose([
                tv.transforms.Resize(256),
                # tv.transforms.CenterCrop(224),
                tv.transforms.ToTensor(),
                # tv.transforms.Normalize(mean, std)
                ])
        te_dataset = patd.PatchDataset(path_to_images=args.data_root,
                                        fold='valid',
                                        transform=transform_test)
        te_loader = DataLoader(te_dataset, batch_size=args.batch_size, shuffle=False, num_workers=24)
             
        trainer.train(model, tr_loader, te_loader, args.adv_train)
    
    elif args.todo == 'test':
        te_dataset = patd.PatchDataset(path_to_images=args.data_root,
                                        fold='test',
                                        transform=tv.transforms.Compose([
                                            tv.transforms.Resize(256),
                                            tv.transforms.ToTensor(),
                                            ]))
        te_loader = DataLoader(te_dataset, batch_size=1, shuffle=False, num_workers=1)
        checkpoint = torch.load(args.load_checkpoint)
        model.load_state_dict(checkpoint)
        std_acc, adv_acc = trainer.test(model, te_loader, adv_test=True, use_pseudo_label=False, if_AUC=True)
        print("std acc: %.4f, adv_acc: %.4f" % (std_acc * 100, adv_acc * 100))

    else:
        raise NotImplementedError
示例#3
0
    model = models.resnet50()
    model_ = models.resnet50()
    model.fc = nn.Linear(model.fc.in_features, args.nclass)
    model_.fc = nn.Linear(model_.fc.in_features, args.nclass)
    load_model(model, args.checkpoint_path)
    load_model(model_, args.checkpoint_path_)
    grad_cam = GradCam(model=model, feature_module=model.layer4, \
                       target_layer_names=["2"], use_cuda=args.use_cuda)
    grad_cam_ = GradCam(model=model_, feature_module=model_.layer4, \
                       target_layer_names=["2"], use_cuda=args.use_cuda)

    transform_test = tv.transforms.Compose([
            tv.transforms.Resize(args.resolution),
            tv.transforms.ToTensor()
            ])
    te_dataset = patd.PatchDataset(path_to_images=args.image_path, fold='test',
                                transform=tv.transforms.ToTensor())
    te_loader = DataLoader(te_dataset, batch_size=1, shuffle=False, num_workers=1)

    counter = 0
    for data, label in te_loader:
        if int(np.sum(label.squeeze().numpy())) > 0:
            disease = ''
            for i in range(int(np.sum(label.squeeze().numpy()))):
                disease_index = np.nonzero(label.squeeze().numpy())[0][i]
                dis_temp = te_dataset.PRED_LABEL[disease_index]
                disease = disease + ' ' + dis_temp
        data, label = tensor2cuda(data), tensor2cuda(label)
        target_category = None
        grayscale_cam, lab = grad_cam(data, target_category, te_dataset.PRED_LABEL)
        grayscale_cam_, lab_ = grad_cam_(data, target_category, te_dataset.PRED_LABEL)
        # print(grayscale_cam.shape)
示例#4
0
    
    # plt.show()
    if save:
        plt.savefig(name, format='png', dpi=500, bbox_inches = 'tight', pad_inches = 0)
    plt.close()
    
    return Zi


if __name__ == '__main__':
    data_root = '../CheXpert_Dataset/images_256/images/'
    transform_test = tv.transforms.Compose([
            tv.transforms.Resize(256),
            tv.transforms.ToTensor()
            ])
    te_dataset = patd.PatchDataset(path_to_images=data_root, fold='test',
                                transform=transform_test)
    test_loader = DataLoader(te_dataset, batch_size=1, shuffle=False, num_workers=1)

    # model = models.resnet50(pretrained=False)
    model = resnet50dsbn(pretrained=False)
    num_classes=8
    model.fc = nn.Linear(model.fc.in_features, num_classes)
    modelpath = './checkpoint/cxr/chexpert_linf_full_/checkpoint_best.pth'
    if os.path.exists(modelpath):
        load_model(model, modelpath)
        print('Model reloaded!!!')
    else:
        print('No checkpoint was found!!!')
    # if torch.cuda.is_available():
    #     model = model.cuda()
示例#5
0
import matplotlib.pyplot as plt 

perturbation_type = 'linf'
# out_num = 100
args = parser()
max_epsilon = 0.002
alpha = max_epsilon / 2
save_folder = '%s_%s' % (args.dataset, args.affix)
img_folder = os.path.join(args.log_root, save_folder)
makedirs(img_folder)
args = parser()
# label_dict = LabelDict(args.dataset)

te_dataset = patd.PatchDataset(path_to_images=args.data_root,
                                fold='test',
                                transform=tv.transforms.Compose([
                                            tv.transforms.Resize(256),
                                            tv.transforms.ToTensor(),
                                            ]))
te_loader = DataLoader(te_dataset, batch_size=1, shuffle=True, num_workers=1)

adv_list = []
in_list = []
# model = MLP_bns(input_dim=32*32, output_dim=1)
model = models.resnet50(pretrained=False)
num_classes=8
model.fc = nn.Linear(model.fc.in_features, num_classes)
load_model(model, args.load_checkpoint)
if torch.cuda.is_available():
    model.cuda()
attack = FastGradientSignUntargeted(model, 
                                    max_epsilon,