如何正确使用vgg模型的中间层 [英] How to correctly use an intermediate layer of a vgg model

查看:492
本文介绍了如何正确使用vgg模型的中间层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所做的是:

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.

推荐答案

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

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

这篇关于如何正确使用vgg模型的中间层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆