如何正确使用VGG模型的中间层

我所做的是:

from keras.applications.vgg16 import VGG16from keras.layers import *from keras.models import Modelimport numpy as np vgg_model = VGG16(weights='imagenet', include_top=False, input_shape = (224,224, 3)) block5_conv3 = vgg_model.get_layer("block5_conv3").outputinput_image = Input(shape=(224,224, 3), name='image_input')vgg_out = vgg_model(input_image)f0 = Flatten()(block5_conv3)test_model = Model(inputs=input_image, outputs=f0)print(test_model.summary())

但我得到了以下错误信息:

Traceback (most recent call last):  File "test.py", line 15, in <module>    test_model = Model(inputs=input_image, outputs=f0)  File "C:\Users\wzhou\AppData\Local\Continuum\Anaconda2\envs\tensorflow\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper    return func(*args, **kwargs)  File "C:\Users\wzhou\AppData\Local\Continuum\Anaconda2\envs\tensorflow\lib\site-packages\keras\engine\network.py", line 93, in __init__    self._init_graph_network(*args, **kwargs)  File "C:\Users\wzhou\AppData\Local\Continuum\Anaconda2\envs\tensorflow\lib\site-packages\keras\engine\network.py", line 237, in _init_graph_network    self.inputs, self.outputs)  File "C:\Users\wzhou\AppData\Local\Continuum\Anaconda2\envs\tensorflow\lib\site-packages\keras\engine\network.py", line 1430, in _map_graph_network    str(layers_with_complete_input))ValueError: Graph disconnected: cannot obtain value for tensor Tensor("input_1:0", shape=(?, 224, 224, 3), dtype=float32) at layer "input_1". The following previous layers were accessed without issue: []

我觉得我的做法有问题,但无法找出正确的方法。


回答:

在这种情况下,无需定义Input层。你可以使用VGG模型的input属性:

vgg_model = VGG16(weights='imagenet', include_top=False, input_shape = (224,224, 3)) block5_conv3 = vgg_model.get_layer("block5_conv3").outputf0 = Flatten()(block5_conv3)test_model = Model(inputs=vgg_model.input, outputs=f0)

或者,你可以定义并使用后端函数

from keras import backend as K# ... (使用上述代码,除了最后一行)func = K.function([vgg_model.input], [f0])# 调用它:outputs = func([your_image_arrays])

Related Posts

在使用k近邻算法时,有没有办法获取被使用的“邻居”?

我想找到一种方法来确定在我的knn算法中实际使用了哪些…

Theano在Google Colab上无法启用GPU支持

我在尝试使用Theano库训练一个模型。由于我的电脑内…

准确性评分似乎有误

这里是代码: from sklearn.metrics…

Keras Functional API: “错误检查输入时:期望input_1具有4个维度,但得到形状为(X, Y)的数组”

我在尝试使用Keras的fit_generator来训…

如何使用sklearn.datasets.make_classification在指定范围内生成合成数据?

我想为分类问题创建合成数据。我使用了sklearn.d…

如何处理预测时不在训练集中的标签

已关闭。 此问题与编程或软件开发无关。目前不接受回答。…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注