简体   繁体   中英

Extracting Transfer learning output from CNN Keras

How to take the intermediate Transfer learning output. ? Eg:

from keras.models import Sequential
from keras.layers import Dense
# ... Other Imports..

from tensorflow.keras.applications.resnet50 import ResNet50
model = Sequential()
resnet = ResNet50(include_top = False, pooling = 'avg', weights = 'imagenet')
model.add(resnet)
model.add(Dense(10, activation = 'softmax'))
model.layers[0].trainable = False

Tried:

layer_output=model.get_layer('resnet').output
layer_output=model.get_layer('resnet').output
intermediate_model=tf.keras.models.Model(inputs=model.input,outputs=layer_output)

There's an unresolved issue in Tensorflow on this problem. According to the issue, you need to pass inputs of both outer model and inner model to get the output of inner model.

import numpy as np

layer_output = model.get_layer("resnet50").output
intermediate_model = tf.keras.models.Model(inputs=[model.input, resnet.input], outputs=[layer_output])

input_data = np.random.rand(1, 224, 224, 3)
result = intermediate_model.predict([input_data, input_data])

print(result[0].shape)
(7, 7, 2048)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM