Using the first 3 layers of a pretrained network in Keras

I want to use the 3rd layer's output of the VGG16 network. The error is like below:

UserWarning: Model inputs must come from `keras.layers.Input` (thus holding past layer metadata), they cannot be the output of a previous non-Input layer. Here, a tensor specified as input to your model was not an Input tensor, it was generated by layer input_1.
Note that input tensors are instantiated via `tensor = keras.layers.Input(shape)`.
The tensor that caused the issue was: input_1:0
  str(x.name))
Traceback (most recent call last):

The code I'm using is below:

from keras import Model
from keras import applications

vgg_model = applications.VGG16(include_top=True, weights='imagenet')
vgg_model.summary()
layers = [l for l in vgg_model.layers]

first_layers = layers[0:3]

result_model = Model(input=layers[0].input, output=first_layers[2](first_layers[1](first_layers[0](layers[0].input))))
print("success")
result_model.summary()

My eventual goal is to take this output and send it to another process and it will continue from 4th layer.

How can I split the neural network into two like this?

Topic vgg16 keras tensorflow deep-learning neural-network

Category Data Science


Defining a new network using a part of a pretained network in Keras is best done layer by layer:

from tensorflow.keras.models       import Sequential 
from tensorflow.keras.applications import VGG16

vgg_model = VGG16(include_top=True, weights='imagenet')

model = Sequential()
model.add(vgg_model.layers[0])
model.add(vgg_model.layers[1])
model.add(vgg_model.layers[2])
model.add(vgg_model.layers[3])
model.summary()

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.