通过Keras,我基于VGG16和一些自定义层创建了功能性API模型:
input_layer = layers.Input(shape=(150, 150, 3), name="model_input")
conv_base = VGG16(weights="imagenet", include_top=False, input_tensor=input_layer)
cust_model = conv_base(input_layer)
cust_model = layers.Flatten()(cust_model)
cust_model = layers.Dense(256, activation="relu")(cust_model)
cust_model = layers.Dense(1, activation="sigmoid")(cust_model)
final_model = models.Model(input=input_layer, output=cust_model)
... # model training etc. (works fine)
final_model.save("models/custom_vgg16.h5")
在另一个脚本中,我想加载该模型并创建另一个自定义模型:
model_vgg16 = load_model("models/custom_vgg16.h5")
layer_input = model_vgg16.get_layer("model_input").input
layer_outputs = [layer.output for layer in model_vgg16.get_layer("vgg16").layers[1:]]
activation_model = models.Model(inputs=layer_input, outputs=layer_outputs)
但是最后一行导致以下错误:
ValueError: Graph disconnected: cannot obtain value for tensor Tensor("model_input_1:0", shape=(?, 150, 150, 3), dtype=float32) at layer "model_input". The following previous layers were accessed without issue: []
我在SO和其他站点上发现了一些相关问题,但是这些似乎都不是我在这里面临的问题。你有什么想法吗?
PS:layer_outputs
的内容是这样的:
Tensor("block1_conv1/Relu:0", shape=(?, 150, 150, 64), dtype=float32)
Tensor("block1_conv2/Relu:0", shape=(?, 150, 150, 64), dtype=float32)
Tensor("block1_pool/MaxPool:0", shape=(?, 75, 75, 64), dtype=float32)
Tensor("block2_conv1/Relu:0", shape=(?, 75, 75, 128), dtype=float32)
Tensor("block2_conv2/Relu:0", shape=(?, 75, 75, 128), dtype=float32)
Tensor("block2_pool/MaxPool:0", shape=(?, 37, 37, 128), dtype=float32)
Tensor("block3_conv1/Relu:0", shape=(?, 37, 37, 256), dtype=float32)
Tensor("block3_conv2/Relu:0", shape=(?, 37, 37, 256), dtype=float32)
Tensor("block3_conv3/Relu:0", shape=(?, 37, 37, 256), dtype=float32)
Tensor("block3_pool/MaxPool:0", shape=(?, 18, 18, 256), dtype=float32)
Tensor("block4_conv1/Relu:0", shape=(?, 18, 18, 512), dtype=float32)
Tensor("block4_conv2/Relu:0", shape=(?, 18, 18, 512), dtype=float32)
Tensor("block4_conv3/Relu:0", shape=(?, 18, 18, 512), dtype=float32)
Tensor("block4_pool/MaxPool:0", shape=(?, 9, 9, 512), dtype=float32)
Tensor("block5_conv1/Relu:0", shape=(?, 9, 9, 512), dtype=float32)
Tensor("block5_conv2/Relu:0", shape=(?, 9, 9, 512), dtype=float32)
Tensor("block5_conv3/Relu:0", shape=(?, 9, 9, 512), dtype=float32)
Tensor("block5_pool/MaxPool:0", shape=(?, 4, 4, 512), dtype=float32)
答案 0 :(得分:1)
我找到了解决方案。必须直接使用vgg16
层/模型的输入层。
因此,为了记录:
layer_input = model_vgg16.get_layer("vgg16").get_layer("model_input").input