| 214 | |
| 215 | # FGSM attack code |
| 216 | def fgsm_attack(image, epsilon, data_grad): |
| 217 | # Collect the element-wise sign of the data gradient |
| 218 | sign_data_grad = data_grad.sign() |
| 219 | # Create the perturbed image by adjusting each pixel of the input image |
| 220 | perturbed_image = image + epsilon*sign_data_grad |
| 221 | # Adding clipping to maintain [0,1] range |
| 222 | perturbed_image = torch.clamp(perturbed_image, 0, 1) |
| 223 | # Return the perturbed image |
| 224 | return perturbed_image |
| 225 | |
| 226 | # restores the tensors to their original scale |
| 227 | def denorm(batch, mean=[0.1307], std=[0.3081]): |