python - 如何使用预训练的keras模型作为模型add函数的参数?

标签 python keras pre-trained-model

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

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

我在仅使用 native 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 中的层。

关于python - 如何使用预训练的keras模型作为模型add函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54727957/

相关文章:

Python|Keras : ValueError: Error when checking target: expected conv2d_3 to have 4 dimensions, 但得到了形状为 (1006, 5) 的数组

python - 3D 张量上的 Keras 点/点层行为

python - 为什么 plt.imshow() 不显示图像?

c++ - 将 boost python 枚举作为参数传递

neural-network - Keras:使用 VGG16 检测特定的非通用项目?

tensorflow - 如何加载图形检查点 (.ckpt) 并使用 SavedModelBuilder 将其保存为 protobuf,而不声明任何 tf.Variables?

nlp - 最新的预训练多语言词嵌入

python - 在 ~/.bashrc 中使用 PYTHONPATH 导入 Python 模块不起作用

python - 通过从 CSV 中读取列来绘制图表

python - 安装了tensorflow,但是pycharm忽略了它