How to retrieve a layer in Caffe

2019-07-14 02:39发布

问题:

Given a caffe.Net object, what's the best way to access a particular layer?
Right now I only figured how to iterate over them, which is not very useful:

for i in range(n_layers):
  print net.layers[i].type

回答1:

You can get all the layers' names by

all_names = [n for n in net._layer_names]

of course if you want to inspect the values of the learned parameters, you can see how it's done in this net surgery example.

For instance, if you want to inspect the filters of conv1 layer (assuming you have a layer with that name in your model) you can access

In [1]: net.params['conv1'][0].data.shape
Out[1]: (64, 3, 3, 3)

And the bias term of this layer

In [2]: net.params['conv1'][1].data.shape
Out[2]: (64,)

As you can see, this is the first layer of an image processing net, it has 64 filters acting on 3x3 patches of BGR (3 channels) input.

If you already fed data through the net (using net.forward, or net.backward) you can inspect the responses of the different layers to the specific inputs fed through the net:

In [3]: net.blobs['conv1'].data.shape
Out[3]: (1, 64, 198, 198)

The output shape of conv1 layer is 198x198 pixels with 64 channels (there are 64 filters in this layer) and the batch size is 1.
If you performed a backward pass as well, you can also inspect the gradients computed at this layer:

In [4]: net.blobs['conv1'].diff.shape
Out[4]: (1, 64, 198, 198)