如何将最后一层预训练网络作为张量输入以在 Keras 中展平

How to input last layer of pretrained network as tensor to flatten in Keras

我正在尝试制作一个具有两个输出的模型,一个用于分类,另一个用于回归。我使用来自 Keras 的预训练 VGG16 作为卷积特征提取器。但是当我尝试在两个输出序列中构建下一个展平层时,我得到输入不是张量的错误。如何确保仅将卷积基的最后一层作为下一层的输入?

conv_base = VGG16(include_top = False,
                  weights = 'imagenet')
conv_base.trainable = False
with tf.variable_scope('classification_head', reuse=tf.AUTO_REUSE):
    x = Flatten()(conv_base.layers[-1])
    x = Dense()(x)

错误:

ValueError: Layer flatten_1 was called with an input that isn't a symbolic tensor. Received type: class 'keras.layers.pooling.MaxPooling2D'. Full input: [keras.layers.pooling.MaxPooling2D object at 0xc2855c9b0]. All inputs to the layer should be tensors.

获得了所需的张量:

features = conv_base.output 
print(features)

Tensor("block5_pool/MaxPool:0", shape=(?, 11, 14, 512), dtype=float32)