Keras 属性错误:'Functional'对象没有属性'shape'。

5

尝试将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
2个回答

3
你遇到该错误的原因是需要提供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)

0
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

这个有效了。


1
如果您检查我的答案,就不需要像您在这个答案中那样强制提供输入。 - Timbus Calin
实际上,您可以通过以下方式两次提供输入: 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)) - Timbus Calin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接