Path: blob/master/examples/keras_recipes/ipynb/subclassing_conv_layers.ipynb
5294 views
Customizing the convolution operation of a Conv2D layer
Author: lukewood
Date created: 11/03/2021
Last modified: 11/03/2021
Description: This example shows how to implement custom convolution layers using the Conv.convolution_op() API.
Introduction
You may sometimes need to implement custom versions of convolution layers like Conv1D and Conv2D. Keras enables you do this without implementing the entire layer from scratch: you can reuse most of the base convolution layer and just customize the convolution op itself via the convolution_op() method.
This method was introduced in Keras 2.7. So before using the convolution_op() API, ensure that you are running Keras version 2.7.0 or greater.
A Simple StandardizedConv2D implementation
There are two ways to use the Conv.convolution_op() API. The first way is to override the convolution_op() method on a convolution layer subclass. Using this approach, we can quickly implement a StandardizedConv2D as shown below.
The other way to use the Conv.convolution_op() API is to directly call the convolution_op() method from the call() method of a convolution layer subclass. A comparable class implemented using this approach is shown below.
Example Usage
Both of these layers work as drop-in replacements for Conv2D. The following demonstration performs classification on the MNIST dataset.
Conclusion
The Conv.convolution_op() API provides an easy and readable way to implement custom convolution layers. A StandardizedConvolution implementation using the API is quite terse, consisting of only four lines of code.