简体   繁体   中英

How to create Keras Model() from VGG layers

I have created a custom Keras model using the VGG16 base, which I train and save:

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")

In another script I now want to load that saved network and crete a new Keras Model object from it, using the custom networks input and the VGG16 layers as outputs:

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)

But the last line leads to the following error:

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: []

Any ideas what I might be missing here?

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

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

You can also get the input node by selecting the inputs directly from the model.

model_vgg16.input

you have to give input with respect to your image size for example if your image is of size 150,150,3 then try this

model = models.Sequential()
model.add(conv_base)
model.add(Input(shape=(150,150,3)))
model.add(layers.Flatten())
model.add(layers.Dense(256, activation="relu"))
model.add(layers.Dense(1, activation="sigmoid"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM