0

An example of replacing a lambda with a subclass in code is as follows:

scale = tf.Variable(1.)
scale_layer = tf.keras.layers.Lambda(lambda x: x * scale)

Because scale_layer does not directly track the scale variable, it will not appear in scale_layer.trainable_weights and will therefore not be trained if scale_layer is used in a Model. A better pattern is to write a subclassed Layer:

class ScaleLayer(tf.keras.layers.Layer):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.scale = tf.Variable(1.)

    def call(self, inputs):
        return inputs * self.scale

According to the instructions above, how should the lambda section in the last line of the code below be changed?

def grouped_convolution_block(inputs, num_filters, kernel_size, strides, cardinality): 
# Adds a grouped convolution block
    group_list = [] 
    grouped_channels = int(num_filters / cardinality)
    
    for c in range(cardinality):
        x = tf.keras.layers.Lambda(lambda z: z[:, :, c * grouped_channels:(c + 1) * grouped_channels])(inputs)

What is the subclass layer that replaces the last line (lambda part) of code?

1 Answer 1

0
  1. Define the custom layer:
class GroupSliceLayer(tf.keras.layers.Layer):
    def __init__(self, start, end, **kwargs):
        super().__init__(**kwargs)
        self.start = start
        self.end = end

    def call(self, inputs):
        return inputs[:, :, self.start:self.end]
  1. Use the custom layer in your grouped_convolution_block function:
def grouped_convolution_block(inputs, num_filters, kernel_size, strides, cardinality): 
    # Adds a grouped convolution block
    group_list = [] 
    grouped_channels = int(num_filters / cardinality)
    
    for c in range(cardinality):
        start = c * grouped_channels
        end = (c + 1) * grouped_channels
        x = GroupSliceLayer(start, end)(inputs)
        group_list.append(x)


Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.