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

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

正在尝试将 Densenet121 功能块添加到模型中。 我需要用这种格式编写 Keras 模型,而不是使用

model=Sequential() 
model.add()

方法 函数有什么问题,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

出现该错误的原因是您需要提供 base_modelinput_shape,而不是每个人说的 base_model

替换此行:model = keras.models.Model(inputs=base_model, outputs = img_dense_encoder)

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

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

这有效..