Writing Your Custom Layer

There are two components to adding a custom layer:

  • Adding the layer configuration class: extends org.deeplearning4j.nn.conf.layers.Layer
  • Adding the layer implementation class: implements org.deeplearning4j.nn.api.LayerThe configuration layer ((1) above) class handles the settings. It’s the one you woulduse when constructing a MultiLayerNetwork or ComputationGraph. You can add customsettings here, and use them in your layer.

The implementation layer ((2) above) class has parameters, and handles network forwardpass, backpropagation, etc. It is created from the org.deeplearning4j.nn.conf.layers.Layer.instantiate(…)method. In other words: the instantiate method is how we go from the configurationto the implementation; MultiLayerNetwork or ComputationGraph will call this methodwhen initializing the

An example of these are CustomLayer (the configuration class) and CustomLayerImpl (theimplementation class). Both of these classes have extensive comments regardingtheir methods.

You’ll note that in Deeplearning4j there are two DenseLayer clases, two GravesLSTM classes,etc: the reason is because one is for the configuration, one is for the implementation.We have not followed this “same name” pattern here to hopefully avoid confusion.

Testing Your Custom Layer

Once you have added a custom layer, it is necessary to run some tests to ensureit is correct.

These tests should at a minimum include the following:

  • Tests to ensure that the JSON configuration (to/from JSON) works correctlyThis is necessary for networks with your custom layer to function with bothmodel serialization (saving) and Spark training.
  • Gradient checks to ensure that the implementation is correct.

Example

A full custom layer example is available in our examples repository.

API