首页 > 解决方案 > 使用 tf.keras.application 时如何获得中间输出

问题描述

tf.keras.application包含许多著名的神经网络链接VGGdensenet等等mobilenet。举tf.keras.application.MobileNet个例子,我感兴趣的不仅仅是最终的输出,还有中间层的输出,我在重新训练网络的时候怎么能得到所有这些输出。

可能会有model.get_output_at(index)帮助。但是,每次我调用这个函数时,我都会得到一个,DeferredTensor因为我不能同时转发数据。有没有方便的方法?

先谢谢了~

标签: pythontensorflowkeras

解决方案


我建议您阅读 keras文档

一种简单的方法是创建一个新的Model,它将输出您感兴趣的图层:

from keras.models import Model

model = ...  # create the original model

layer_name = 'my_layer'
intermediate_layer_model = Model(inputs=model.input,
                                 outputs=model.get_layer(layer_name).output)
intermediate_output = intermediate_layer_model.predict(data)

或者,您可以构建一个 Keras 函数,该函数将在给定特定输入的情况下返回特定层的输出,例如:

from keras import backend as K

# with a Sequential model
get_3rd_layer_output = K.function([model.layers[0].input],
                                  [model.layers[3].output])
layer_output = get_3rd_layer_output([x])[0]

同样,您可以直接构建 Theano 和 TensorFlow 函数。

请注意,如果您的模型在训练和测试阶段有不同的行为(例如,如果它使用 Dropout、BatchNormalization 等),您需要将学习阶段标志传递给您的函数:

get_3rd_layer_output = K.function([model.layers[0].input, K.learning_phase()],
                                  [model.layers[3].output])

# output in test mode = 0
layer_output = get_3rd_layer_output([x, 0])[0]

# output in train mode = 1
layer_output = get_3rd_layer_output([x, 1])[0]

这是fchollet自己写的另一个类似的答案: 如何获得给定数据的隐藏层表示?


推荐阅读