def __getitem__(self, idx): """ Resizes and normalizes tensors for Inception_v3 :param idx: ``int``, index :return: Tensor([C, H, W]) """ img = self.data[idx] img = resize(img, size=(299, 299)) img = normalize(img, mean=torch.tensor([0.485, 0.456, 0.406]), std=torch.tensor([0.229, 0.224, 0.225])) return img.squeeze(0)
def preprocess(self, images): """ Preprocess images Args: images: (N, 3, H, W), Input images Return x: (N, 3, H, W), Preprocessed images """ x = images if self.pretrained: # Create a mask for padded pixels mask = (x == 0) # Match ResNet pretrained preprocessing x = normalize(x, mean=self.norm_mean, std=self.norm_std) # Make padded pixels = 0 x[mask] = 0 return x
def fgsm_attack(images, epsilon, gradients, means, stds): # We should apply adversarial attack in unnormalized domain images = denormalize(images, means, stds) images = torch.clamp(images, 0, 1) # Collect the element-wise sign of the data gradient gradient_signs = gradients.sign().float() # Create the perturbed image by adjusting each pixel of the input image perturbed_images = images + epsilon * gradient_signs # Adding clipping to maintain [0,1] range perturbed_images = torch.clamp(perturbed_images, 0, 1) # Normalize the images back perturbed_images = normalize(perturbed_images, means, stds) # Return the perturbed image return perturbed_images