-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMask and PGD Attack.py
443 lines (298 loc) · 11.5 KB
/
Mask and PGD Attack.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import os
import json
import time
import random
import numpy as np
import pandas as pd
import pydicom
from PIL import Image
from sklearn.model_selection import train_test_split
import warnings
warnings.filterwarnings("ignore")
# In[2]:
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torch.nn.functional as F
from torchvision import transforms
from torch.utils.data import Dataset, DataLoader
import torchvision.models as models
from sklearn.metrics import precision_recall_fscore_support, roc_auc_score
import matplotlib.pyplot as plt
import sklearn.metrics as metrics
# In[3]:
get_ipython().system('nvidia-smi')
# In[4]:
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="6"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device
# In[5]:
config = dict(
saved_path="saved/random.pt",
best_saved_path = "saved/random_best.pt",
lr=0.001,
EPOCHS = 3,
BATCH_SIZE = 32,
IMAGE_SIZE = 32,
TRAIN_VALID_SPLIT = 0.2,
device=device,
SEED = 42,
pin_memory=True,
num_workers=3,
USE_AMP = True,
channels_last=False)
# In[6]:
random.seed(config['SEED'])
# If you or any of the libraries you are using rely on NumPy, you can seed the global NumPy RNG
np.random.seed(config['SEED'])
# Prevent RNG for CPU and GPU using torch
torch.manual_seed(config['SEED'])
torch.cuda.manual_seed(config['SEED'])
torch.backends.cudnn.benchmarks = True
torch.backends.cudnn.deterministic = True
torch.backends.cuda.matmul.allow_tf32 = True
# The flag below controls whether to allow TF32 on cuDNN. This flag defaults to True.
torch.backends.cudnn.allow_tf32 = True
# In[7]:
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop((config['IMAGE_SIZE'],config['IMAGE_SIZE'])),
#transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'val': transforms.Compose([
transforms.Resize((config['IMAGE_SIZE'],config['IMAGE_SIZE'])),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'test': transforms.Compose([
transforms.Resize((config['IMAGE_SIZE'],config['IMAGE_SIZE'])),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
# # SHVN dataset
# In[8]:
train_data = torchvision.datasets.SVHN(root='../Images', split = 'train',
download=True, transform=data_transforms['train'])
train_dl = torch.utils.data.DataLoader(train_data, batch_size=32,shuffle=True, num_workers = config['num_workers'],
pin_memory = config['pin_memory'])
test_data = torchvision.datasets.SVHN(root='../Images', split='test',
download=True, transform=data_transforms['test'])
test_dl = torch.utils.data.DataLoader(test_data, batch_size=32,shuffle=True, num_workers = config['num_workers'],
pin_memory = config['pin_memory'])
valid_dl = test_dl
# In[9]:
valid_data = test_data
classes = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
# In[10]:
import matplotlib.pyplot as plt
a = iter(valid_dl)
b = next(a)
print(b[1])
plt.imshow(b[0][0][0])
# In[11]:
def train_model(model,criterion,optimizer,num_epochs=10):
since = time.time()
batch_ct = 0
example_ct = 0
best_acc = 0.3
for epoch in range(num_epochs):
print('Epoch {}/{}'.format(epoch, num_epochs - 1))
print('-' * 10)
run_corrects = 0
#Training
model.train()
for x,y in train_dl: #BS=32 ([BS,3,224,224], [BS,4])
if config['channels_last']:
x = x.to(config['device'], memory_format=torch.channels_last) #CHW --> #HWC
else:
x = x.to(config['device'])
y = y.to(config['device']) #CHW --> #HWC
optimizer.zero_grad()
#optimizer.zero_grad(set_to_none=True)
######################################################################
train_logits = model(x) #Input = [BS,3,224,224] (Image) -- Model --> [BS,4] (Output Scores)
_, train_preds = torch.max(train_logits, 1)
train_loss = criterion(train_logits,y)
train_loss = criterion(train_logits,y)
run_corrects += torch.sum(train_preds == y.data)
train_loss.backward() # Backpropagation this is where your W_gradient
loss=train_loss
optimizer.step() # W_new = W_old - LR * W_gradient
example_ct += len(x)
batch_ct += 1
if ((batch_ct + 1) % 400) == 0:
train_log(loss, example_ct, epoch)
########################################################################
#validation
model.eval()
running_loss = 0.0
running_corrects = 0
total = 0
# Disable gradient calculation for validation or inference using torch.no_rad()
with torch.no_grad():
for x,y in valid_dl:
if config['channels_last']:
x = x.to(config['device'], memory_format=torch.channels_last) #CHW --> #HWC
else:
x = x.to(config['device'])
y = y.to(config['device'])
valid_logits = model(x)
_, valid_preds = torch.max(valid_logits, 1)
valid_loss = criterion(valid_logits,y)
running_loss += valid_loss.item() * x.size(0)
running_corrects += torch.sum(valid_preds == y.data)
total += y.size(0)
epoch_loss = running_loss / len(valid_data)
epoch_acc = running_corrects.double() / len(valid_data)
train_acc = run_corrects.double() / len(train_data)
print("Train Accuracy",train_acc.cpu())
print("Validation Loss is {}".format(epoch_loss))
print("Validation Accuracy is {}\n".format(epoch_acc.cpu()))
if epoch_acc.cpu()>best_acc:
print('One of the best validation accuracy found.\n')
#torch.save(model.state_dict(), config['best_saved_path'])
best_acc = epoch_acc.cpu()
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(
time_elapsed // 60, time_elapsed % 60))
#torch.save(model.state_dict(), config['saved_path'])
def train_log(loss, example_ct, epoch):
loss = float(loss)
print(f"Loss after " + str(example_ct).zfill(5) + f" examples: {loss:.3f}")
# # Architecture-1: Squeezenet
# In[12]:
squeezenet = torchvision.models.squeezenet1_0(pretrained=True)
squeezenet.classifier[1] = nn.Conv2d(512, 10, kernel_size=(1, 1), stride=(1, 1))
model = squeezenet
# In[13]:
model = model.to(config['device'])
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(),lr=config['lr'])
train_model(model,criterion,optimizer,num_epochs=10)
# In[ ]:
# # Mask Based attack
# In[14]:
def mask_based_attack(model, images, labels, epsilon=0.03):
model.eval()
images = images.clone().detach().requires_grad_(True)
outputs = model(images)
loss = F.cross_entropy(outputs, labels)
model.zero_grad()
loss.backward()
grad = images.grad.data
sign = grad.sign()
perturbed_images = images + epsilon * sign
perturbed_images = torch.clamp(perturbed_images, 0, 1)
return perturbed_images
# In[15]:
def evaluate_mask_attack(epsilon = 0.03):
correct = 0
total = 0
#with torch.no_grad():
for data in test_dl:
images, labels = data
images, labels = images.to(device), labels.to(device)
# Set requires_grad flag to True
images.requires_grad = True
# Compute the gradient
outputs = model(images)
loss = criterion(outputs, labels)
model.zero_grad()
grad = torch.autograd.grad(loss, images, retain_graph=True, only_inputs=True)[0]
data_grad = grad.data
# Generate adversarial examples
perturbed_images = mask_based_attack(model, images, labels, epsilon)
outputs = model(perturbed_images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
# Reset requires_grad flag back to False
images.requires_grad = False
print('For Epsilon = ', epsilon)
print('Accuracy on perturbed mask attack data: %d %%' % (100 * correct / total))
evaluate_mask_attack()
# In[16]:
for e in [0,0.01,0.05,0.1]:
evaluate_mask_attack(e)
print()
# # PGD Attack
# In[17]:
def pgd_attack(images, targets, net, criterion, epsilon=0.1, alpha=0.01, num_iter=40):
# images = images.clone().detach().to(device)
# targets = targets.clone().detach().to(device)
# Create a perturbation vector of the same shape as the input images
perturbation = torch.zeros_like(images).to(device)
for i in range(num_iter):
# Zero out the gradients
net.zero_grad()
# Compute the loss and the gradients of the loss with respect to the inputs
loss = criterion(net(images + perturbation), targets)
loss.backward()
# Add the gradient of the loss to the perturbation vector
perturbation = (perturbation + alpha * torch.sign(images.grad.data)).clamp(-epsilon, epsilon)
# Clamp the perturbed images to the valid range
perturbed_images = (images + perturbation).clamp(0, 1)
# Zero out the gradients
net.zero_grad()
# Compute the loss and the gradients of the loss with respect to the inputs
loss = criterion(net(perturbed_images), targets)
loss.backward()
# Return the perturbed images
return perturbed_images
# In[18]:
def evaluate_pgd(epsilon = 0.03):
correct = 0
total = 0
#with torch.no_grad():
for data in test_dl:
images, labels = data
images, labels = images.to(device), labels.to(device)
# Set requires_grad flag to True
images.requires_grad = True
# Compute the gradient
outputs = model(images)
loss = criterion(outputs, labels)
# Generate adversarial examples
perturbed_images = pgd_attack(images, labels, model, criterion, epsilon)
outputs = model(perturbed_images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
# Reset requires_grad flag back to False
images.requires_grad = False
print('For Epsilon = ', epsilon)
print('Accuracy on PGD attacked data: %d %%' % (100 * correct / total))
evaluate_pgd()
# In[19]:
for e in [0,0.01,0.05,0.1]:
evaluate_pgd(e)
print()
# # Architecture-2: Shufflenet
# In[20]:
shufflenet = models.shufflenet_v2_x1_0(pretrained = True)
shufflenet.fc = nn.Linear(in_features = 1024, out_features = 10, bias=True)
model = shufflenet
# In[21]:
model = model.to(config['device'])
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(),lr=config['lr'])
train_model(model,criterion,optimizer,num_epochs=10)
# In[22]:
# Mask Attack
for e in [0,0.01,0.03,0.05,0.1]:
evaluate_mask_attack(e)
print()
# In[ ]:
# PGD Attack
for e in [0,0.01,0.03,0.05,0.1]:
evaluate_pgd(e)
print()
# In[ ]: