98
98
import numpy as np
99
99
import matplotlib .pyplot as plt
100
100
101
- # NOTE: This is a hack to get around "User-agent" limitations when downloading MNIST datasets
102
- # see, https://github.com/pytorch/vision/issues/3497 for more information
103
- from six .moves import urllib
104
- opener = urllib .request .build_opener ()
105
- opener .addheaders = [('User-agent' , 'Mozilla/5.0' )]
106
- urllib .request .install_opener (opener )
107
-
108
101
109
102
######################################################################
110
103
# Implementation
140
133
epsilons = [0 , .05 , .1 , .15 , .2 , .25 , .3 ]
141
134
pretrained_model = "data/lenet_mnist_model.pth"
142
135
use_cuda = True
136
+ # Set random seed for reproducibility
137
+ torch .manual_seed (42 )
143
138
144
139
145
140
######################################################################
@@ -178,18 +173,18 @@ def forward(self, x):
178
173
test_loader = torch .utils .data .DataLoader (
179
174
datasets .MNIST ('../data' , train = False , download = True , transform = transforms .Compose ([
180
175
transforms .ToTensor (),
181
- ])),
176
+ ])),
182
177
batch_size = 1 , shuffle = True )
183
178
184
179
# Define what device we are using
185
180
print ("CUDA Available: " ,torch .cuda .is_available ())
186
- device = torch .device ("cuda" if ( use_cuda and torch .cuda .is_available () ) else "cpu" )
181
+ device = torch .device ("cuda" if use_cuda and torch .cuda .is_available () else "cpu" )
187
182
188
183
# Initialize the network
189
184
model = Net ().to (device )
190
185
191
186
# Load the pretrained model
192
- model .load_state_dict (torch .load (pretrained_model , map_location = 'cpu' ))
187
+ model .load_state_dict (torch .load (pretrained_model , weights_only = True , map_location = 'cpu' ))
193
188
194
189
# Set the model in evaluation mode. In this case this is for the Dropout layers
195
190
model .eval ()
@@ -289,7 +284,7 @@ def test( model, device, test_loader, epsilon ):
289
284
if final_pred .item () == target .item ():
290
285
correct += 1
291
286
# Special case for saving 0 epsilon examples
292
- if ( epsilon == 0 ) and ( len (adv_examples ) < 5 ) :
287
+ if epsilon == 0 and len (adv_examples ) < 5 :
293
288
adv_ex = perturbed_data .squeeze ().detach ().cpu ().numpy ()
294
289
adv_examples .append ( (init_pred .item (), final_pred .item (), adv_ex ) )
295
290
else :
@@ -300,7 +295,7 @@ def test( model, device, test_loader, epsilon ):
300
295
301
296
# Calculate final accuracy for this epsilon
302
297
final_acc = correct / float (len (test_loader ))
303
- print ("Epsilon: {}\t Test Accuracy = {} / {} = {}" . format ( epsilon , correct , len ( test_loader ), final_acc ) )
298
+ print (f "Epsilon: { epsilon } \t Test Accuracy = { correct } / { len ( test_loader ) } = { final_acc } " )
304
299
305
300
# Return the accuracy and an adversarial example
306
301
return final_acc , adv_examples
@@ -386,9 +381,9 @@ def test( model, device, test_loader, epsilon ):
386
381
plt .xticks ([], [])
387
382
plt .yticks ([], [])
388
383
if j == 0 :
389
- plt .ylabel ("Eps: {}" . format ( epsilons [i ]) , fontsize = 14 )
384
+ plt .ylabel (f "Eps: { epsilons [i ]} " , fontsize = 14 )
390
385
orig ,adv ,ex = examples [i ][j ]
391
- plt .title ("{ } -> {}" . format ( orig , adv ) )
386
+ plt .title (f" { orig } -> { adv } " )
392
387
plt .imshow (ex , cmap = "gray" )
393
388
plt .tight_layout ()
394
389
plt .show ()
0 commit comments