How to correctly use an intermediate layer of a vgg model

泄露秘密 提交于 2019-12-10 22:42:18

问题


What I did is:

from keras.applications.vgg16 import VGG16
from keras.layers import *
from keras.models import Model
import numpy as np 

vgg_model = VGG16(weights='imagenet', include_top=False, input_shape = (224,224, 3)) 

block5_conv3 = vgg_model.get_layer("block5_conv3").output

input_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())

But I got the following error message:

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

I feel something is wrong with the way that I did it but couldn't figure out the right way.


回答1:


There is no need to define an Input layer in this case. You can use the input property of VGG model:

vgg_model = VGG16(weights='imagenet', include_top=False, input_shape = (224,224, 3)) 

block5_conv3 = vgg_model.get_layer("block5_conv3").output
f0 = Flatten()(block5_conv3)

test_model = Model(inputs=vgg_model.input, outputs=f0)

Alternatively, you can define and use a backend function:

from keras import backend as K

# ... (use the code above except the last line)

func = K.function([vgg_model.input], [f0])

# to call it:
outputs = func([your_image_arrays])


来源:https://stackoverflow.com/questions/52230874/how-to-correctly-use-an-intermediate-layer-of-a-vgg-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!