caffe Custom Python Layers Layer Template


import caffe

class My_Custom_Layer(caffe.Layer):
    def setup(self, bottom, top):
    def forward(self, bottom, top):
    def reshape(self, bottom, top):

    def backward(self, bottom, top):

So important things to remember:

  • Your custom layer has to inherit from caffe.Layer (so don't forget to import caffe);
  • You must define the four following methods: setup, forward, reshape and backward;
  • All methods have a top and a bottom parameters, which are the blobs that store the input and the output passed to your layer. You can access it using top[i].data or bottom[i].data, where i is the index of the blob in case you have more than one upper or lower blob.

- Setup method

The Setup method is called once during the lifetime of the execution, when Caffe is instantiating all layers. This is where you will read parameters, instantiate fixed-size buffers.

- Reshape method

Use the reshape method for initialization/setup that depends on the bottom blob (layer input) size. It is called once when the network is instantiated.

- Forward method

The Forward method is called for each input batch and is where most of your logic will be.

- Backward method

The Backward method is called during the backward pass of the network. For example, in a convolution-like layer, this would be where you would calculate the gradients. This is optional (a layer can be forward-only).