Mahmudur Rahman
Mahmudur Rahman

Reputation: 77

TF: Model SubClassing | AttributionError: 'NoneType' object has no attribute 'compile'

I'm trying to implement sub-classing for model definition in tf.keras in following way and facing following attribution error.

def my_model(Model):
    def __init__(self, dim):
        super(my_model, self).__init__(**kwargs)
        self.efnet  = efn.EfficientNetB0(input_shape=(dim, 3), include_top = False, weights = 'imagenet')
        self.gap    = L.GlobalAveragePooling2D()
        self.bn     = L.BatchNormalization()
        self.denseA = L.Dense(784, activation='relu', name = 'dense_A')
        self.out    = L.Dense(1, activation='sigmoid')
    
    def call(self, inputs):
        x     = self.efnet(inputs)
        x_gap = self.gap(x)
        bn    = self.bn(x_gap)
        den_A = self.denseA(bn)
        drop  = self.drop(den_A)
        return self.out(drop)

dim = (124,124)
model = my_model((dim)

Error

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-e8086e70a144> in <module>()
     27 dim = (124,124)
     28 model = my_model(dim)
---> 29 model.compile(
     30     optimizer='adam',
     31     loss = 'binary_crossentropy',

AttributeError: 'NoneType' object has no attribute 'compile'

Environment

OS: Windows OS
TF Ver. tf 2.1

Reproducibility Here is the reproducible code in colab.


TIA

Upvotes: 0

Views: 2657

Answers (1)

Innat
Innat

Reputation: 17219

It should be class not function.

Instead of def my_model(Model): , it should be class my_model(Model): . And also we need to build the model further. Here is the full code:


class my_model(Model):
    def __init__(self, dim):
        super(my_model, self).__init__(**kwargs)
        self.efnet  = efn.EfficientNetB0(input_shape=(dim, 3), include_top = False, weights = 'imagenet')
        self.gap    = L.GlobalAveragePooling2D()
        self.bn     = L.BatchNormalization()
        self.denseA = L.Dense(784, activation='relu', name = 'dense_A')
        self.out    = L.Dense(1, activation='sigmoid')
    
    def call(self, inputs):
        x     = self.efnet(inputs)
        x_gap = self.gap(x)
        bn    = self.bn(x_gap)
        den_A = self.denseA(bn)
        drop  = self.drop(den_A)
        return self.out(drop)

dim = (124,124)
model = my_model((dim)
model.build((None, *dim))
model.compile(...)
model.summary()

Upvotes: 1

Related Questions