Skip to content

Instantly share code, notes, and snippets.

@Paulescu
Last active June 27, 2022 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Paulescu/a1f1116178ee00d6b7464e5a21c52bf2 to your computer and use it in GitHub Desktop.
Save Paulescu/a1f1116178ee00d6b7464e5a21c52bf2 to your computer and use it in GitHub Desktop.
import numpy as np
from cleverhans.torch.attacks.fast_gradient_method import fast_gradient_method
eps = 0.1
# load image
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
x = feature_extractor(image, return_tensors="pt").pixel_values
# fast gradient sign method
x_fgm = fast_gradient_method(
lambda x: model(x).logits, # maps normalized image to model logits
x, # original image we want to modify
eps, # max size of the perturbation
np.inf #l-infinite distance to measure the perturbation
)
# print results
new_image = inverse_feature_extractor(x_fgm)
print('Predicted class: ', image2class(new_image))
new_image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment