|
| 1 | +#Experiment Objectives: |
| 2 | +#1. Generate Attack from model j and test accuracies, L2 Distances and Reconstructions on model i (!=j) |
| 3 | + |
| 4 | +import torch |
| 5 | +import numpy as np |
| 6 | +import torch |
| 7 | +import torch.nn as nn |
| 8 | +import torch.nn.functional as F |
| 9 | +from tqdm import tqdm |
| 10 | +import os |
| 11 | +import matplotlib.pyplot as plt |
| 12 | +from advertorch.attacks import LinfPGDAttack, GradientSignAttack, CarliniWagnerL2Attack, LinfBasicIterativeAttack |
| 13 | +# import seaborn as sns |
| 14 | + |
| 15 | +import sys |
| 16 | +sys.path.insert(0,'/raid/sdas_ma/Adversarial_CapsNet_Pytorch/') |
| 17 | +from model.net import * |
| 18 | +from model.cnn_net import * |
| 19 | +from utils.training import * |
| 20 | +from data.data import * |
| 21 | + |
| 22 | + |
| 23 | +base_path = '/raid/sdas_ma/Adversarial_CapsNet_Pytorch/' |
| 24 | +model_path = "/raid/sdas_ma/Adversarial_CapsNet_Pytorch/weights/"#os.path.join(os.getcwd(), "weights") |
| 25 | + |
| 26 | +Caps_args = { |
| 27 | + 'DATASET_NAME':'mnist', |
| 28 | + 'num_classes':10, |
| 29 | + |
| 30 | + 'USE_CUDA': True if torch.cuda.is_available() else False, |
| 31 | + 'BATCH_SIZE': 512, |
| 32 | + |
| 33 | + ##For Decoder |
| 34 | + 'num_features':160, |
| 35 | + 'LReLU_negative_slope':0.1, |
| 36 | + 'input_height':28, |
| 37 | + 'input_width':28, |
| 38 | + 'input_channel':1, |
| 39 | +} |
| 40 | + |
| 41 | +CNN_args = { |
| 42 | + 'DATASET_NAME':'mnist', |
| 43 | + 'num_classes':10, |
| 44 | + |
| 45 | + 'USE_CUDA': True if torch.cuda.is_available() else False, |
| 46 | + 'BATCH_SIZE': 256, |
| 47 | + #For Decoder |
| 48 | + 'num_features':160, |
| 49 | + 'LReLU_negative_slope':0.1, |
| 50 | + 'input_height':28, |
| 51 | + 'input_width':28, |
| 52 | + 'input_channel':1, |
| 53 | + 'type':'plusCR', |
| 54 | +} |
| 55 | + |
| 56 | +class Caps_Config: |
| 57 | + def __init__(self, dataset='mnist'): |
| 58 | + # CNN (cnn) |
| 59 | + self.cnn_in_channels = 1 |
| 60 | + self.cnn_out_channels = 12 |
| 61 | + self.cnn_kernel_size = 15 |
| 62 | + |
| 63 | + # Primary Capsule (pc) |
| 64 | + self.pc_num_capsules = 1 |
| 65 | + self.pc_in_channels = 12 |
| 66 | + self.pc_out_channels = 16 |
| 67 | + self.pc_kernel_size = 8 |
| 68 | + self.pc_num_routes = 7 * 7 |
| 69 | + |
| 70 | + # Digit Capsule 1 (dc) |
| 71 | + self.dc_num_capsules = 49 |
| 72 | + self.dc_num_routes = 7 * 7 |
| 73 | + self.dc_in_channels = 16 |
| 74 | + self.dc_out_channels = 16 #1 |
| 75 | + |
| 76 | + # Digit Capsule 2 (dc) |
| 77 | + self.dc_2_num_capsules = 10 |
| 78 | + self.dc_2_num_routes = 7 * 7 |
| 79 | + self.dc_2_in_channels = 16 #1 |
| 80 | + self.dc_2_out_channels = 16 |
| 81 | + |
| 82 | + # Decoder |
| 83 | + self.input_width = 28 |
| 84 | + self.input_height = 28 |
| 85 | + |
| 86 | +class CNN_Config: |
| 87 | + def __init__(self, dataset='mnist'): |
| 88 | + # CONV1 |
| 89 | + self.conv1_in = 1 |
| 90 | + self.conv1_out = 12 |
| 91 | + self.conv1_kernel_size = 15 |
| 92 | + |
| 93 | + # CONV2 |
| 94 | + self.conv2_in = 12 |
| 95 | + self.conv2_out = 16 |
| 96 | + self.conv2_kernel_size = 8 |
| 97 | + |
| 98 | + # FC1 |
| 99 | + self.fc1_in = 7 * 7 * 16 |
| 100 | + self.fc1_out = 784 |
| 101 | + |
| 102 | + # FC1 |
| 103 | + self.fc2_in = 784 |
| 104 | + self.fc2_out = 160 |
| 105 | + |
| 106 | +torch.manual_seed(1) |
| 107 | + |
| 108 | +################Loading Dataset#################### |
| 109 | +cmnistlist = ["brightness", "canny_edges", "dotted_line", "fog" , "glass_blur" , "identity", "impulse_noise", "motion_blur", "rotate", "scale", "shear" , "shot_noise" , "spatter", "stripe", "translate", "zigzag"] |
| 110 | +cmnistpath = os.path.join(base_path,"data/mnist_c/") |
| 111 | + |
| 112 | +def test_n_l2(model, model_name): |
| 113 | + net.eval() |
| 114 | + Und_l2 = {key:torch.tensor([],dtype=torch.bool) for key in cmnistlist} |
| 115 | + l2_distances_all = {key:torch.tensor([],dtype=torch.int16) for key in cmnistlist} |
| 116 | + |
| 117 | + for corruption in cmnistlist: |
| 118 | + datapath = os.path.join(cmnistpath, corruption) |
| 119 | + unnorm_data = torch.tensor(np.load(os.path.join(datapath, "test_images.npy"))/255).permute((0,3,1,2)) |
| 120 | + labels = torch.tensor(np.load(os.path.join(datapath, "test_labels.npy"))) |
| 121 | + if(labels.min()==1): |
| 122 | + labels -= 1 |
| 123 | + unnorm_data, labels = unnorm_data.cuda().type(torch.cuda.FloatTensor), labels.cuda() |
| 124 | + #normalizing |
| 125 | + data = (unnorm_data - 0.1307)/0.3081 |
| 126 | + with torch.no_grad(): |
| 127 | + output, reconstructions, max_length_indices = net(data) |
| 128 | + l2_distances = ((reconstructions.view(unnorm_data.size(0),-1)-unnorm_data.view(unnorm_data.size(0), -1))**2).sum(1).squeeze().detach() |
| 129 | + Und_l2[corruption] = torch.cat((Und_l2[corruption], (max_length_indices != labels).detach().cpu())) |
| 130 | + l2_distances_all[corruption] = torch.cat((l2_distances_all[corruption], l2_distances.detach().cpu())) |
| 131 | + Und_l2[corruption] = Und_l2[corruption].numpy() |
| 132 | + l2_distances_all[corruption] = l2_distances_all[corruption].numpy() |
| 133 | + print(model_name," : " ,corruption," : ",np.sum(Und_l2[corruption])/100," // ",np.sum(l2_distances_all[corruption][Und_l2[corruption]]<45)/100) |
| 134 | + np.save(os.path.join(base_path , "results", str("cmnist"+model_name+"Undl2.npy")), Und_l2) |
| 135 | + np.save(os.path.join(base_path , "results", str("cmnist"+model_name+"l2_dist.npy")), l2_distances_all) |
| 136 | + |
| 137 | +def capsnet(): |
| 138 | + config = Caps_Config() |
| 139 | + net = CapsNet(Caps_args, config) |
| 140 | + # capsule_net = torch.nn.DataParallel(capsule_net) |
| 141 | + if Caps_args['USE_CUDA']: |
| 142 | + net = net.cuda() |
| 143 | + net.load_state_dict(torch.load(os.path.join(model_path, 'CapsNet_mnist.pth'), map_location='cpu')) |
| 144 | + return net |
| 145 | + |
| 146 | +def CNN(model_type): |
| 147 | + CNN_args['type'] = model_type |
| 148 | + config = CNN_Config() |
| 149 | + net = CNNnet(CNN_args, config) |
| 150 | + net.load_state_dict(torch.load(os.path.join(model_path, 'CNN'+model_type+'_mnist.pth'), map_location='cpu')) |
| 151 | + if CNN_args['USE_CUDA']: |
| 152 | + net = net.cuda() |
| 153 | + return net |
| 154 | + |
| 155 | +def load_model(model_name): |
| 156 | + if(model_name=="capsnet"): |
| 157 | + net = capsnet() |
| 158 | + return net |
| 159 | + else: |
| 160 | + net = CNN(model_name) |
| 161 | + return net |
| 162 | + |
| 163 | +model_name_list = ["capsnet", "plusCR", "plusR"] |
| 164 | +for model_name in model_name_list: |
| 165 | + net = load_model(model_name) |
| 166 | + test_n_l2(net, model_name) |
| 167 | + |
| 168 | + |
| 169 | + |
0 commit comments