python - 使用 tf.keras.application 时如何获得中间输出
问题描述
tf.keras.application
包含许多著名的神经网络链接VGG
,densenet
等等mobilenet
。举tf.keras.application.MobileNet
个例子,我感兴趣的不仅仅是最终的输出,还有中间层的输出,我在重新训练网络的时候怎么能得到所有这些输出。
可能会有model.get_output_at(index)
帮助。但是,每次我调用这个函数时,我都会得到一个,DeferredTensor
因为我不能同时转发数据。有没有方便的方法?
先谢谢了~
解决方案
我建议您阅读 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自己写的另一个类似的答案: 如何获得给定数据的隐藏层表示?
推荐阅读
- android - 如何让用户界面像小米商店?
- jenkins - 在没有自己的仓库的情况下为下游管道存储 Jenkinsfile 的位置
- oracle - 如何使用 jpaRepository 从 oracle 数据库中获取序列号?
- c# - 如何使用依赖注入在 3 层应用程序中维护 DRY 规则?
- activemq - java.io.IOException:ActiveMQ 服务启动时无法绑定错误
- java - 带有allowOverwrite的IgniteDataStreamer比putAll慢?
- node.js - 尝试更新父文档猫鼬中的子文档
- c# - DateTime.Parse 有时会在管道上抛出 FormatException
- javascript - 在角度 8 中从 index.html 向组件内注入动态 html
- django - Django制作与其他字段(对象)值相关的字段