如何使用预训练的 keras 模型作为模型添加函数的参数?

How to use a pretrained keras model to be a parameter to a Model's add function?

我正在将 python 深度学习中的预训练模型教程应用于 kaggle 上的数据集。下面是我的 CNN 架构代码,虽然很简单,但我收到了这个错误:

TypeError: The added layer must be an instance of class Layer. Found: keras.engine.training.Model object at 0x7fdb6a780f60

我在使用原生 keras 时已经能够做到这一点,但我 运行 在尝试使用 tensorflow 2.0

时遇到了问题
from keras.applications.vgg16 import VGG16

base = VGG16(weights='../input/vgg16/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5',
             include_top=False,
             input_shape=(150,225,3))

model = models.Sequential()
model.add(base)
model.add(layers.Flatten())
model.add(layers.Dense(256, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

base.summary()

您需要切换到 functional API,因为顺序模型只接受图层:

from keras.applications.vgg16 import VGG16

base = VGG16(weights='../input/vgg16/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5',
             include_top=False,
             input_shape=(150,225,3))

in = Input(shape=(150,225,3))
base_out = base(in)
out = Flatten()(base_out)
out = Dense(256, activation='relu')
out = Dense(1, activation='sigmoid')
model = Model(in, out)
model.summary()

请注意如何将模型用作函数 API 中的层。