Custom layers

View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook

We recommend using tf.keras as a high-level API for building neural networks. That said, most TensorFlow APIs are usable with eager execution.

import tensorflow as tf
print(tf.config.list_physical_devices('GPU'))
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU'), PhysicalDevice(name='/physical_device:GPU:1', device_type='GPU'), PhysicalDevice(name='/physical_device:GPU:2', device_type='GPU'), PhysicalDevice(name='/physical_device:GPU:3', device_type='GPU')]

Layers: common sets of useful operations

Most of the time when writing code for machine learning models you want to operate at a higher level of abstraction than individual operations and manipulation of individual variables.

Many machine learning models are expressible as the composition and stacking of relatively simple layers, and TensorFlow provides both a set of many common layers as well as easy ways for you to write your own application-specific layers either from scratch or as the composition of existing layers.

TensorFlow includes the full Keras API in the tf.keras package, and the Keras layers are very useful when building your own models.

# In the tf.keras.layers package, layers are objects. To construct a layer,
# simply construct the object. Most layers take as a first argument the number
# of output dimensions / channels.
layer = tf.keras.layers.Dense(100)
# The number of input dimensions is often unnecessary, as it can be inferred
# the first time the layer is used, but it can be provided if you want to
# specify it manually, which is useful in some complex models.
layer = tf.keras.layers.Dense(10, input_shape=(None, 5))

The full list of pre-existing layers can be seen in the documentation. It includes Dense (a fully-connected layer), Conv2D, LSTM, BatchNormalization, Dropout, and many others.

# To use a layer, simply call it.
layer(tf.zeros([10, 5]))
<tf.Tensor: shape=(10, 10), dtype=float32, numpy=
array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]], dtype=float32)>
# Layers have many useful methods. For example, you can inspect all variables
# in a layer using `layer.variables` and trainable variables using
# `layer.trainable_variables`. In this case a fully-connected layer
# will have variables for weights and biases.
layer.variables
[<tf.Variable 'dense_1/kernel:0' shape=(5, 10) dtype=float32, numpy=
 array([[ 0.07330298,  0.14658362, -0.1593974 , -0.272908  , -0.19214004,
          0.22034258, -0.07681805,  0.16928357,  0.578489  , -0.3933804 ],
        [-0.20256034, -0.3201593 , -0.08189708,  0.48770434, -0.1683318 ,
          0.09442174, -0.22532725, -0.28716284, -0.07927346, -0.43820667],
        [-0.1543808 ,  0.42554277, -0.2560555 ,  0.09486747, -0.3410151 ,
         -0.05457103, -0.6154055 , -0.4919873 , -0.1757274 , -0.1647934 ],
        [ 0.4562549 ,  0.38436514,  0.32118964,  0.24889952,  0.44032902,
          0.11407197, -0.4720816 ,  0.4467768 , -0.12260407, -0.5083143 ],
        [ 0.27884638,  0.41720766,  0.29349357,  0.01260734, -0.51639855,
          0.5712243 ,  0.47127682, -0.44931155,  0.481785  ,  0.14226294]],
       dtype=float32)>,
 <tf.Variable 'dense_1/bias:0' shape=(10,) dtype=float32, numpy=array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)>]
# The variables are also accessible through nice accessors
layer.kernel, layer.bias
(<tf.Variable 'dense_1/kernel:0' shape=(5, 10) dtype=float32, numpy=
 array([[ 0.07330298,  0.14658362, -0.1593974 , -0.272908  , -0.19214004,
          0.22034258, -0.07681805,  0.16928357,  0.578489  , -0.3933804 ],
        [-0.20256034, -0.3201593 , -0.08189708,  0.48770434, -0.1683318 ,
          0.09442174, -0.22532725, -0.28716284, -0.07927346, -0.43820667],
        [-0.1543808 ,  0.42554277, -0.2560555 ,  0.09486747, -0.3410151 ,
         -0.05457103, -0.6154055 , -0.4919873 , -0.1757274 , -0.1647934 ],
        [ 0.4562549 ,  0.38436514,  0.32118964,  0.24889952,  0.44032902,
          0.11407197, -0.4720816 ,  0.4467768 , -0.12260407, -0.5083143 ],
        [ 0.27884638,  0.41720766,  0.29349357,  0.01260734, -0.51639855,
          0.5712243 ,  0.47127682, -0.44931155,  0.481785  ,  0.14226294]],
       dtype=float32)>,
 <tf.Variable 'dense_1/bias:0' shape=(10,) dtype=float32, numpy=array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)>)

Implementing custom layers

The best way to implement your own layer is extending the tf.keras.Layer class and implementing:

  1. __init__ , where you can do all input-independent initialization
  2. build, where you know the shapes of the input tensors and can do the rest of the initialization
  3. call, where you do the forward computation

Note that you don't have to wait until build is called to create your variables, you can also create them in __init__. However, the advantage of creating them in build is that it enables late variable creation based on the shape of the inputs the layer will operate on. On the other hand, creating variables in __init__ would mean that shapes required to create the variables will need to be explicitly specified.

class MyDenseLayer(tf.keras.layers.Layer):
  def __init__(self, num_outputs):
    super(MyDenseLayer, self).__init__()
    self.num_outputs = num_outputs

  def build(self, input_shape):
    self.kernel = self.add_weight("kernel",
                                  shape=[int(input_shape[-1]),
                                         self.num_outputs])

  def call(self, inputs):
    return tf.matmul(inputs, self.kernel)

layer = MyDenseLayer(10)
_ = layer(tf.zeros([10, 5])) # Calling the layer `.builds` it.
print([var.name for var in layer.trainable_variables])
['my_dense_layer/kernel:0']

Overall code is easier to read and maintain if it uses standard layers whenever possible, as other readers will be familiar with the behavior of standard layers. If you want to use a layer which is not present in tf.keras.layers, consider filing a github issue or, even better, sending us a pull request!

Models: Composing layers

Many interesting layer-like things in machine learning models are implemented by composing existing layers. For example, each residual block in a resnet is a composition of convolutions, batch normalizations, and a shortcut. Layers can be nested inside other layers.

Typically you inherit from keras.Model when you need the model methods like: Model.fit,Model.evaluate, and Model.save (see Custom Keras layers and models for details).

One other feature provided by keras.Model (instead of keras.layers.Layer) is that in addition to tracking variables, a keras.Model also tracks its internal layers, making them easier to inspect.

For example here is a ResNet block:

class ResnetIdentityBlock(tf.keras.Model):
  def __init__(self, kernel_size, filters):
    super(ResnetIdentityBlock, self).__init__(name='')
    filters1, filters2, filters3 = filters

    self.conv2a = tf.keras.layers.Conv2D(filters1, (1, 1))
    self.bn2a = tf.keras.layers.BatchNormalization()

    self.conv2b = tf.keras.layers.Conv2D(filters2, kernel_size, padding='same')
    self.bn2b = tf.keras.layers.BatchNormalization()

    self.conv2c = tf.keras.layers.Conv2D(filters3, (1, 1))
    self.bn2c = tf.keras.layers.BatchNormalization()

  def call(self, input_tensor, training=False):
    x = self.conv2a(input_tensor)
    x = self.bn2a(x, training=training)
    x = tf.nn.relu(x)

    x = self.conv2b(x)
    x = self.bn2b(x, training=training)
    x = tf.nn.relu(x)

    x = self.conv2c(x)
    x = self.bn2c(x, training=training)

    x += input_tensor
    return tf.nn.relu(x)


block = ResnetIdentityBlock(1, [1, 2, 3])
_ = block(tf.zeros([1, 2, 3, 3]))
block.layers
[<keras.src.layers.convolutional.conv2d.Conv2D at 0x7fb4301504f0>,
 <keras.src.layers.normalization.batch_normalization.BatchNormalization at 0x7fb43014ce50>,
 <keras.src.layers.convolutional.conv2d.Conv2D at 0x7fb43c0a37f0>,
 <keras.src.layers.normalization.batch_normalization.BatchNormalization at 0x7fb43c0a3ca0>,
 <keras.src.layers.convolutional.conv2d.Conv2D at 0x7fb43c53d130>,
 <keras.src.layers.normalization.batch_normalization.BatchNormalization at 0x7fb440248730>]
len(block.variables)
18
block.summary()
Model: ""
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 conv2d (Conv2D)             multiple                  4         
                                                                 
 batch_normalization (Batch  multiple                  4         
 Normalization)                                                  
                                                                 
 conv2d_1 (Conv2D)           multiple                  4         
                                                                 
 batch_normalization_1 (Bat  multiple                  8         
 chNormalization)                                                
                                                                 
 conv2d_2 (Conv2D)           multiple                  9         
                                                                 
 batch_normalization_2 (Bat  multiple                  12        
 chNormalization)                                                
                                                                 
=================================================================
Total params: 41 (164.00 Byte)
Trainable params: 29 (116.00 Byte)
Non-trainable params: 12 (48.00 Byte)
_________________________________________________________________

Much of the time, however, models which compose many layers simply call one layer after the other. This can be done in very little code using tf.keras.Sequential:

my_seq = tf.keras.Sequential([tf.keras.layers.Conv2D(1, (1, 1),
                                                    input_shape=(
                                                        None, None, 3)),
                             tf.keras.layers.BatchNormalization(),
                             tf.keras.layers.Conv2D(2, 1,
                                                    padding='same'),
                             tf.keras.layers.BatchNormalization(),
                             tf.keras.layers.Conv2D(3, (1, 1)),
                             tf.keras.layers.BatchNormalization()])
my_seq(tf.zeros([1, 2, 3, 3]))
<tf.Tensor: shape=(1, 2, 3, 3), dtype=float32, numpy=
array([[[[0., 0., 0.],
         [0., 0., 0.],
         [0., 0., 0.]],

        [[0., 0., 0.],
         [0., 0., 0.],
         [0., 0., 0.]]]], dtype=float32)>
my_seq.summary()
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 conv2d_3 (Conv2D)           (None, None, None, 1)     4         
                                                                 
 batch_normalization_3 (Bat  (None, None, None, 1)     4         
 chNormalization)                                                
                                                                 
 conv2d_4 (Conv2D)           (None, None, None, 2)     4         
                                                                 
 batch_normalization_4 (Bat  (None, None, None, 2)     8         
 chNormalization)                                                
                                                                 
 conv2d_5 (Conv2D)           (None, None, None, 3)     9         
                                                                 
 batch_normalization_5 (Bat  (None, None, None, 3)     12        
 chNormalization)                                                
                                                                 
=================================================================
Total params: 41 (164.00 Byte)
Trainable params: 29 (116.00 Byte)
Non-trainable params: 12 (48.00 Byte)
_________________________________________________________________

Next steps

Now you can go back to the previous notebook and adapt the linear regression example to use layers and models to be better structured.