如何从VGG图层创建Keras Model()

时间:2019-05-16 10:28:21

标签: python keras keras-layer vgg-net

我使用VGG16基础创建了一个自定义Keras模型,我对其进行了训练和保存:

from keras.applications import VGG16
from keras import models
from keras import layers

conv_base = VGG16(weights="imagenet", include_top=False)

model = models.Sequential()
model.add(conv_base)
model.add(layers.Flatten())
model.add(layers.Dense(256, activation="relu"))
model.add(layers.Dense(1, activation="sigmoid"))
...
model.save("models/custom_vgg16.h5")

在另一个脚本中,我现在想使用自定义网络输入和VGG16层作为输出来加载保存的网络并从中创建新的Keras Model对象:

from keras.models import load_model
from keras import Model

model_vgg16 = load_model("models/custom_vgg16.h5")

layer_outputs = [layer.output for layer in model_vgg16.get_layer("vgg16").layers[1:]]
activation_model = Model(inputs=model_vgg16.get_layer("vgg16").get_input_at(1), outputs=layer_outputs)

但是最后一行导致以下错误:

ValueError: Graph disconnected: cannot obtain value for tensor Tensor("input_1:0", shape=(?, 150, 150, 3), dtype=float32) at layer "input_1". The following previous layers were accessed without issue: []

有什么主意我可能会在这里错过吗?

2 个答案:

答案 0 :(得分:1)

您要在最后一行的节点索引0处获得输入:

model_vgg16.get_layer('vgg16').get_input_at(0)

答案 1 :(得分:0)

您还可以通过直接从模型中选择输入来获取输入节点。

  

model_vgg16.input