Search code examples
pythontensorflowkerasdeep-learningneural-network

Add new layer error message: The added layer must be an instance of class Layer


I tried add a new layer to my model but I got the error message

TypeError: The added layer must be an instance of class Layer. Found: <class '__main__.New_Layer'>

Almost answer say that all layer should be "tf.keras" or "keras"

but I add "tf.keras.layers.Layer" to New_Layer but not work.

Before add New_Layer, this model can normal execution.

Here is my code

#InceptionResNetV2
conv_base = tf.keras.applications.InceptionResNetV2(weights=None,include_top=False , input_shape=(299,299,3))
conv_base.trainable = True
for layers in conv_base.layers[:-20]:
    conv_base.trainable = False
    
    
class New_Layer(tf.keras.layers.Layer):
    def __init__(self, context,  **kwargs):
        super(New_Layer, self).__init__(**kwargs)
        self.context = context
        
    def call(self, inputs):
        feature_map = inputs
        #get current file name and load new 
        file_name = self.context.get('file_name')
        print(file_name)
        new_image = 
        return tf.concat([feature_map, new_image], axis=-1)


model = tf.keras.Sequential()
model.add(conv_base)
model.add(tf.keras.layers.GlobalAveragePooling2D())
model.add(New_Layer)
model.add(tf.keras.layers.Dense(7,activation='softmax')) 
model.summary()

model.compile(optimizer=Adam(learning_rate=0.001), loss='categorical_crossentropy', metrics=['accuracy'])

Solution

  • Referring to the tensorflow guide:

    model.add(New_Layer(context = ...))