Daniel Voigt Godoy - Deep Learning with PyTorch Step-by-Step A Beginner’s Guide-leanpub

peiying410632
from peiying410632 More from this publisher
22.02.2024 Views

Output{Conv2d(1, 1, kernel_size=(3, 3), stride=(1, 1)): 'conv1',ReLU(): 'relu1',MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1,ceil_mode=False): 'maxp1',Flatten(): 'flatten',Linear(in_features=16, out_features=10, bias=True): 'fc1',ReLU(): 'relu2',Linear(in_features=10, out_features=3, bias=True): 'fc2'}A dictionary is perfect for that: The hook function will take the layer instance as anargument and look its name up in the dictionary!OK, it is time to create a real hook function:visualization = {}def hook_fn(layer, inputs, outputs):name = layer_names[layer]visualization[name] = outputs.detach().cpu().numpy()It is actually quite simple: It looks up the name of the layer and uses it as a key to adictionary defined outside the hook function, which will store the outputsproduced by the hooked layer. The inputs are being ignored in this function.We can make a list of the layers we’d like to get the outputs from, loop through thelist of named modules, and hook our function to the desired layers, keeping thehandles in another dictionary:layers_to_hook = ['conv1', 'relu1', 'maxp1', 'flatten','fc1', 'relu2', 'fc2']handles = {}for name, layer in modules:if name in layers_to_hook:handles[name] = layer.register_forward_hook(hook_fn)Visualizing Filters and More! | 399

Everything is in place now! The only thing left to do is to actually call the model, soa forward pass is triggered, the hooks are executed, and the outputs to all theselayers are stored in the visualization dictionary.Let’s fetch one mini-batch from the validation loader and use the predict()method of our StepByStep class (which will then call the trained model):images_batch, labels_batch = iter(val_loader).next()logits = sbs_cnn1.predict(images_batch)Now, if everything went well, our visualization dictionary should contain one keyfor each layer we hooked a function to:visualization.keys()Outputdict_keys(['conv1', 'relu1', 'maxp1', 'flatten', 'fc1', 'relu2','fc2'])Bingo! They are all there! But, before checking what’s stored inside it, let’s removethe hooks:for handle in handles.values():handle.remove()handles = {}Make sure to always remove the hooks after they have servedtheir purpose to avoid unnecessary operations that may slowdown your model.Maybe I got you hooked (sorry, I really like puns!), maybe not. Anyway, to make iteasier for you to get some layers hooked so you can take a peek at what they areproducing, we will append some methods to our StepByStep class: attach_hooks()and remove_hooks().First, we create two dictionaries as attributes, visualization and handles, which400 | Chapter 5: Convolutions

Everything is in place now! The only thing left to do is to actually call the model, so

a forward pass is triggered, the hooks are executed, and the outputs to all these

layers are stored in the visualization dictionary.

Let’s fetch one mini-batch from the validation loader and use the predict()

method of our StepByStep class (which will then call the trained model):

images_batch, labels_batch = iter(val_loader).next()

logits = sbs_cnn1.predict(images_batch)

Now, if everything went well, our visualization dictionary should contain one key

for each layer we hooked a function to:

visualization.keys()

Output

dict_keys(['conv1', 'relu1', 'maxp1', 'flatten', 'fc1', 'relu2',

'fc2'])

Bingo! They are all there! But, before checking what’s stored inside it, let’s remove

the hooks:

for handle in handles.values():

handle.remove()

handles = {}

Make sure to always remove the hooks after they have served

their purpose to avoid unnecessary operations that may slow

down your model.

Maybe I got you hooked (sorry, I really like puns!), maybe not. Anyway, to make it

easier for you to get some layers hooked so you can take a peek at what they are

producing, we will append some methods to our StepByStep class: attach_hooks()

and remove_hooks().

First, we create two dictionaries as attributes, visualization and handles, which

400 | Chapter 5: Convolutions

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!