如何为 Tensorflow Hub 模块的特定输入获取所有层的激活?

How to get all layers' activations for a specific input for Tensorflow Hub modules?

我是 Tensorflow Hub 的新手。我想使用 I3D 模块并将该网络微调到另一个数据集,我需要获取最后一个隐藏层以及其他一些层的输出。我想知道是否有办法获得其他层的激活。为 I3D 提供的唯一签名只是 "default"。我认为应该有一种方法可以使用 Tensorflow Hub 模块轻松获取所有层的输出。

import tensorflow_hub as hub
module = hub.Module("https://tfhub.dev/deepmind/i3d-kinetics-600/1", trainable=False)
logits = module(inp)

这将给我最终的图层输出。如何获取其他层的输出,例如第二个卷积层的输出?

https://tfhub.dev/deepmind/i3d-kinetics-400/1(以及 *-600 版本)碰巧只导出最后一层,因此没有适当支持的方法来获取其他层。 (也就是说,您始终可以通过检查图表并按名称选择张量来进行试验,但这确实存在停止使用较新模块或库版本的风险。)

您可以通过名称获取其他图层。以Inception-v3为例:

import tensorflow_hub as hub

module = hub.Module("https://tfhub.dev/google/imagenet/inception_v3/feature_vector/1")
logits = module(inp)

logits 包含所有模型层。您可以通过调用 items():

查看它们
print(logits.items())

这会输出一个包含图中所有层的字典,其中一些如下所示:

dict_items([
('InceptionV3/Mixed_6c', <tf.Tensor 'module_2_apply_image_feature_vector/InceptionV3/InceptionV3/Mixed_6c/concat:0' shape=(1, 17, 17, 768) dtype=float32>), 
('InceptionV3/Mixed_6d', <tf.Tensor 'module_2_apply_image_feature_vector/InceptionV3/InceptionV3/Mixed_6d/concat:0' shape=(1, 17, 17, 768) dtype=float32>), 
('InceptionV3/Mixed_6e', <tf.Tensor 'module_2_apply_image_feature_vector/InceptionV3/InceptionV3/Mixed_6e/concat:0' shape=(1, 17, 17, 768) dtype=float32>),
('default', <tf.Tensor 'module_2_apply_image_feature_vector/hub_output/feature_vector/SpatialSqueeze:0' shape=(1, 2048) dtype=float32>),     
('InceptionV3/MaxPool_5a_3x3', <tf.Tensor 'module_2_apply_image_feature_vector/InceptionV3/InceptionV3/MaxPool_5a_3x3/MaxPool:0' shape=(1, 35, 35, 192) dtype=float32>)])

通常要获取最后一层,您会使用 default:

sess.run(logits['default'])

但是您可以使用它们的名称轻松获取其他图层:

sess.run(logits['InceptionV3/MaxPool_5a_3x3'])