Keras AttributeError: 'Functional' object has no attribute 'shape'

11.9k Views Asked by At

Trying to add Densenet121 functional block to the model. I need Keras model to be written in this format, not using

model=Sequential() 
model.add()

method What's wrong the function, build_img_encod

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-62-69dd207148e0> in <module>()
----> 1 x = build_img_encod()

3 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/input_spec.py in assert_input_compatibility(input_spec, inputs, layer_name)
    164         spec.min_ndim is not None or
    165         spec.max_ndim is not None):
--> 166       if x.shape.ndims is None:
    167         raise ValueError('Input ' + str(input_index) + ' of layer ' +
    168                          layer_name + ' is incompatible with the layer: '

AttributeError: 'Functional' object has no attribute 'shape'
def build_img_encod( ):
    base_model = DenseNet121(input_shape=(150,150,3),
                                 include_top=False,
                                 weights='imagenet')
    for layer in base_model.layers:
            layer.trainable = False
    flatten = Flatten(name="flatten")(base_model)
    img_dense_encoder = Dense(1024, activation='relu',name="img_dense_encoder", kernel_regularizer=regularizers.l2(0.0001))(flatten)
    model = keras.models.Model(inputs=base_model, outputs = img_dense_encoder)
    return model
2

There are 2 best solutions below

0
On BEST ANSWER

The reason why you get that error is that you need to provide the input_shape of the base_model, instead of the base_model per say.

Replace this line: model = keras.models.Model(inputs=base_model, outputs = img_dense_encoder)

with: model = keras.models.Model(inputs=base_model.input, outputs = img_dense_encoder)

2
On
def build_img_encod( ):
    dense = DenseNet121(input_shape=(150,150,3),
                                 include_top=False,
                                 weights='imagenet')
    for layer in dense.layers:
            layer.trainable = False
    img_input = Input(shape=(150,150,3))
    base_model = dense(img_input)
    flatten = Flatten(name="flatten")(base_model)
    img_dense_encoder = Dense(1024, activation='relu',name="img_dense_encoder", kernel_regularizer=regularizers.l2(0.0001))(flatten)
    model = keras.models.Model(inputs=img_input, outputs = img_dense_encoder)
    return model

This worked..