比方说来自 Keras 模型的 Resnet50 的中间输出

Intermediate Output of let' s say Resnet50 from Keras Model

import keras
print(keras.__version__)
#2.3.0

from keras.models import Sequential
from keras.layers import Input, Dense,TimeDistributed
from keras.models import Model

model = Sequential()
resnet = ResNet50(include_top = False, pooling = 'avg', weights = 'imagenet')
model.add(resnet)

model.add(Dense(10, activation = 'relu'))
model.add(Dense(6, activation = 'sigmoid'))
model.summary()

// 训练 // model.fit( .. ) 完成

现在如何只输出层的输出?

model.layers[0]._name='resnet50'
print(model.layers[0].name) # prints resnet50

layer_output = model.get_layer("resnet50").output
intermediate_model = Model(inputs=[model.input, resnet.input], outputs=[layer_output])
result = intermediate_model.predict([x, x])

print(result.shape)
print(result[0].shape)

遇到错误

AttributeError: Layer resnet50 has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use get_output_at(node_index) instead. add Codeadd Markdown

请使用 tf.keras 导入模型和层重试。

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Input, Dense,TimeDistributed
from tensorflow.keras.models import Model

然后运行相同:

model.layers[0]._name='resnet50'
print(model.layers[0].name) # prints resnet50

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

x = tf.ones((1, 250, 250, 3))
result = intermediate_model.predict([x, x])

print(result.shape)
print(result[0].shape)

输出:

resnet50
(1, 2048)
(2048,)