Search code examples
pythonkeraskeras-layervgg-net

Get (input) layer of Keras model after saving and re-loading it from disk


I have loaded, extended, trained a VGG16 network via Keras, then saved it to disk:

from keras.applications import VGG16
from keras import models

conv_base = VGG16(weights="imagenet", include_top=False)
model = models.Sequential()
model.add(conv_base)
...
model.compile(...)
model.fit(...)
model.save("saved_model.h5")

In another script I load that trained model again:

from keras.models import load_model

model_vgg16 = load_model("saved_model.h5")
model_fails = model_vgg16.get_layer("vgg16")
model_fails.input

That last line leads to the following exception:

AttributeError: Layer vgg16 has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use `get_input_at(node_index)` instead.

However, when I do the same for the VGG16 net directly, then it works fine:

from keras.applications import VGG16
from keras.models import load_model

model_works = VGG16(weights='imagenet', include_top=False)
model_works.input

That last line does not lead to an error. So my question is:
How can I access the (input) layer of a saved and then re-loaded Keras model?


Solution

  • After adding the VGG16 model to your custom model, it would have two input nodes: one is the original input node which is accessible using conv_base.get_input_at(0), and another input node which is created for the input from your custom model which would be accessible using conv_base.get_input_at(1) (this is actually the input of the model and is equivalent to model.input). The difference between a node and a layer in Keras has been explained in detail in this answer.