Keras create submodel from last layers of a model

Viewed 423

The following question is a general version of the question

Extracting last layers of keras model as a submodel

Say that I have a keras.model which is feed-forward (not recurrent), but not neccesarily sequential. Is there an effective way of extracting last layers as a submodel, without manually assembling the model ? I want to avoid hardcoding the controlflow of the model.

For example, for a resnet model, i want to extract the part of the model that begins after the 56 x 56 x C convolution-part (which is after layer 50 in the keras implementation)

import tensorflow as tf
from tensorflow.keras.applications.resnet50 import ResNet50

model = ResNet50()
print(model.layers[50].output_shape)
>>> (None, 28, 28, 512)
#the function I seek would be something like
#submodel=create_submodel(big_model = model,layers=model.layers[51:],input_shape = model.layers[50].output_shape)

If there is no "keras.submodel" method, is there at least a way to loop over the layers, that automatically connects to the previous layers, without manually having to implement the logics for a resnet specifically, which would have to be re-done when you do it for a new model?

Bonus question just for my curiosity: There must be a reason why such a functionality doesn't exist. can somebody explain this ?

1 Answers
import tensorflow as tf
from tensorflow.keras.applications.resnet50 import ResNet50

model = ResNet50()
last_layer = tf.keras.models.Model(inputs=model.input, outputs=model.get_layer('block7_pool').output)

Through model.summary() you can get the input to model.get_layer().

Related