Exercise 1
"Evasion" with random noise
Model
import torch
from PIL import Image
from IPython import display
import pandas as pd
import torchvision
from torchvision import transforms
import numpy as np
import matplotlib.pyplot as plt
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(device)
#load the model from the pytorch hub
model = torch.hub.load('pytorch/vision:v0.10.0', 'mobilenet_v2', weights='MobileNet_V2_Weights.DEFAULT', verbose=False)
# Put model in evaluation mode
model.eval()
# put the model on a GPU if available, otherwise CPU
model.to(device);
# Define the transforms for preprocessing
preprocess = transforms.Compose([
transforms.Resize(256), # Resize the image to 256x256
transforms.CenterCrop(224), # Crop the image to 224x224 about the center
transforms.ToTensor(), # Convert the image to a PyTorch tensor
transforms.Normalize(
mean=[0.485, 0.456, 0.406], # Normalize the image with the ImageNet dataset mean values
std=[0.229, 0.224, 0.225] # Normalize the image with the ImageNet dataset standard deviation values
)
]);
def tensor_to_pil(img_tensor):
# tensor: pre-processed tensor object resulting from preprocess(img).unsqueeze(0)
unnormed_tensor = unnormalize(img_tensor)
return transforms.functional.to_pil_image(unnormed_tensor[0])
unnormalize = transforms.Normalize(
mean= [-m/s for m, s in zip([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])],
std= [1/s for s in [0.229, 0.224, 0.225]]
)
# load labels
with open("../data/labels.txt", 'r') as f:
labels = [label.strip() for label in f.readlines()]
# load an example image
img = Image.open("../data/dog.jpg")
plt.imshow(img)
plt.axis('off')
plt.show()
# preprocess the image
img_tensor = preprocess(img).unsqueeze(0)
print(f"Inputs information:\n---------------\nshape:{img_tensor.shape}\n")
# move sample to the right device
img_tensor = img_tensor.to(device)
with torch.no_grad():
output = model(img_tensor)
print(f"Image tensor on device:\n---------------\n{img_tensor.device}\n")
print(f"Inputs information:\n---------------\nshape:{img_tensor.shape}\nclass: {type(img_tensor)}\n")
print(f"Shape of outputs:\n---------------\n{output.shape}\n")
print(f"Pred Index:\n---------------\n{output[0].argmax()}\n")
print(f"Pred Label:\n---------------\n{labels[output[0].argmax()]}\n")
unnormed_img_tensor= unnormalize(img_tensor)
img_pil = transforms.functional.to_pil_image(unnormed_img_tensor[0])
img_pil.show()Exercise
Solution
Last updated