Keras AttributeError:“功能”对象没有属性“形状”

Bhu*_*n S 5 deep-learning keras tensorflow transfer-learning

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

model=Sequential() 
model.add()
Run Code Online (Sandbox Code Playgroud)

方法 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'
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

Tim*_*lin 3

您收到该错误的原因是您需要提供 the input_shapebase_model而不是base_modelper say 。

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

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