Skip to content

Instantly share code, notes, and snippets.

@Paulescu
Created March 14, 2022 12:56
Show Gist options
  • Save Paulescu/a5d085c7680d263ce9681c1cdaac7158 to your computer and use it in GitHub Desktop.
Save Paulescu/a5d085c7680d263ce9681c1cdaac7158 to your computer and use it in GitHub Desktop.
import io
import requests
from PIL import Image
# own imports
from src.model import load_model, preprocess, predict, inverse_preprocess
from src.fgsm import iterative_fast_gradient_sign_
from src.viz import plot
# ------------------------------------------------------------------------------
# 1. PARAMETERS
# load image from a given url
url = 'https://github.com/Paulescu/adversarial-machine-learning/blob/main/images/dog.jpg?raw=true'
# FGSM parameters
epsilon = 0.09
n_steps = 9
alpha = 0.025
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# 2. PROCESSING
# load image from the given url
response = requests.get(url)
img = Image.open(io.BytesIO(response.content))
# load model. This is a time-consuming operation
model = load_model()
# make sure the image from URL is clean, and the model correctly classifies it.
# preprocess original image
x_original = inverse_preprocess(preprocess(img))
# and make sure the model predicts the correct label
x_predictions = predict(model, x_original)
print(x_predictions)
# returns a pair (x_adv, grad) after each FGSM step.
iterator = iterative_fast_gradient_sign_(
model,
preprocess(img),
epsilon,
n_steps=n_steps,
alpha=alpha
)
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# 3. PLOT RESULTS
for x_adv, grad in iterator:
# get model predictions
x_adv_predictions = predict(model, x_adv)
plot(x_original, x_adv, grad, epsilon,
x_label=x_predictions['label'],
x_prob=x_predictions['confidence'],
x_adv_label=x_adv_predictions['label'],
x_adv_prob=x_adv_predictions['confidence'])
# starting image new iteration
x_original = x_adv
x_predictions = predict(model, x_original)
# ------------------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment