-
Notifications
You must be signed in to change notification settings - Fork 9
/
util.py
145 lines (110 loc) · 4.64 KB
/
util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.autograd.gradcheck import zero_gradients
from torch.utils.data import Dataset, DataLoader
import matplotlib.patches as patches
from PIL import Image
def displayMNIST (img):
''' Display MNIST image where pixels are without value 0-1
'''
if not (type(img) is np.ndarray) :
raise TypeError("Only numpy.array is supported")
if not (img.ndim == 3 and img.shape[0] == 1):
raise AttributeError("Expects (1, 28, 28) shape")
img = np.squeeze(img, axis=0) * 255
pixels = img.reshape((28, 28))
# Create 2-inch by 2-inch image
plt.figure(figsize=(1.5,1.5))
plt.imshow(pixels, cmap='gray')
plt.show()
def displayGTSRB (img):
''' Display image from German Traffic Sign Recognition Benchmark
'''
if not (type(img) is np.ndarray) :
raise TypeError("Only numpy.array is supported")
if not (img.ndim == 3 and img.shape[0] == 3):
raise AttributeError("Expects (3, length, width) shape")
# show images, by np.moveaxis(img, 0, -1), i.e., moving the axis from (3, 32, 32) to (32, 32, 3)
plt.figure(figsize=(2,2))
image = plt.imshow(np.moveaxis(img, 0, -1))
plt.grid(False)
def iterative_FGSM_attack (img, label, model):
# eps = 5 * 8 / 225.
eps = 1 * 8 / 225.
steps = 100
norm = float('inf')
# step_alpha = 0.05
step_alpha = 0.01
loss = nn.CrossEntropyLoss()
x, y = Variable(img, requires_grad=True), Variable(label)
result = img
adv = torch.zeros(result.shape)
for step in range(steps):
zero_gradients(x)
out = model(x)
# Returns the maximum value of each row of the input tensor in the given dimension dim
_ , y.data = torch.max(out.data, 1)
if ((not (y.data == label)) and step > 1) :
return result.cpu(), adv.cpu(), True
# print("perturbed input for "+ str(label[0])+ " is now identified to be: "+ str(y.data[0]))
_loss = loss(out, y)
_loss.backward()
normed_grad = step_alpha * torch.sign(x.grad.data)
step_adv = x.data + normed_grad
adv = step_adv - img
adv = torch.clamp(adv, -eps, eps)
result = img + adv
# torch.clamp(input, min, max, out=None) → Tensor
# Clamp all elements in input into the range [min, max] and return a resulting Tensor.
result = torch.clamp(result, 0.0, 1.0)
x.data = result
return result.cpu(), adv.cpu(), False
def iterative_targeted_FGSM_attack (img, label, anotherLabel, model):
eps = 5 * 8 / 225.
#eps = 1 * 8 / 225.
steps = 100
norm = float('inf')
step_alpha = 0.05
#step_alpha = 0.01
loss = nn.CrossEntropyLoss()
x, y = Variable(img, requires_grad=True), Variable(anotherLabel)
result = img
adv = torch.zeros(result.shape)
for step in range(steps):
zero_gradients(x)
out = model(x)
# Returns the maximum value of each row of the input tensor in the given dimension dim
_ , y.data = torch.max(out.data, 1)
if (step == 1 and y.data == anotherLabel):
# It an image directly to the perturbed class. Do nothing
result.cpu(), adv.cpu(), False
if (y.data == anotherLabel and step > 1) :
return result.cpu(), adv.cpu(), True
# print("perturbed input for "+ str(label[0])+ " is now identified to be: "+ str(y.data[0]))
_loss = loss(out, y)
_loss.backward()
normed_grad = step_alpha * torch.sign(x.grad.data)
step_adv = x.data + normed_grad
adv = step_adv - img
adv = torch.clamp(adv, -eps, eps)
result = img + adv
# torch.clamp(input, min, max, out=None) → Tensor
# Clamp all elements in input into the range [min, max] and return a resulting Tensor.
result = torch.clamp(result, 0.0, 1.0)
x.data = result
return result.cpu(), adv.cpu(), False
def drawFrontCar(imgFile, boundingBox = None):
im = np.array(Image.open(imgFile), dtype=np.uint8)
# Create figure and axes
fig,ax = plt.subplots(1)
# Display the image
ax.imshow(im)
if not (boundingBox == None):
# Create a Rectangle patch
rect = patches.Rectangle((int(boundingBox[0]-boundingBox[2]/2),int(boundingBox[1]-boundingBox[3]/2)),int(boundingBox[2]),int(boundingBox[3]),linewidth=1,edgecolor='r',facecolor='none')
# Add the patch to the Axes
ax.add_patch(rect)
plt.show()