Tensorflow 2 Hub:如何获得中间层的输出?

Tensorflow 2 Hub: How can I obtain the output of an intermediate layer?

我正在尝试使用新的 tensorflow 2 实现以下网络 Fots 用于文本检测。作者使用 resnet 作为他们网络的 backbone,所以我的第一个想法是使用tensoflow hub resnet 用于加载预训练网络。但问题是我找不到打印从 tfhub 加载的模块摘要的方法?

有什么办法可以看到tf-hub加载模块的层数吗? 谢谢


更新

不幸的是,resnet 不适用于 tf2-hub,所以我决定使用 resent 的内置 keras 实现,至少在有 hub impl 之前是这样。

下面是我如何使用 tf2.keras.applications 获得 resnet 的中间层:

import numpy as np
import tensorflow as tf
from tensorflow import keras

layers_out = ["activation_9", "activation_21", "activation_39", "activation_48"]

imgs = np.random.randn(2, 640, 640, 3).astype(np.float32)
model = keras.applications.resnet50.ResNet50(input_shape=(640, 640, 3), include_top=False)
intermid_outputs= [model.get_layer(layer_name).output for layer_name in layers_out]
shared_conds = keras.Model(inputs=model.input, outputs=intermid_outputs)
Y = conv_shared(imgs)
shapes = [y.shape for y in Y]
print(shapes)

您可以这样做来检查中间输出:

resnet = hub.Module("https://tfhub.dev/google/imagenet/resnet_v2_50/feature_vector/3")
outputs = resnet(np.random.rand(1,224,224,3), signature="image_feature_vector", as_dict=True)
for intermediate_output in outputs.keys():
    print(intermediate_output)

然后,如果你想 link 中心模块的中间层到你的图的其余部分,你可以这样做:

resnet = hub.Module("https://tfhub.dev/google/imagenet/resnet_v2_50/feature_vector/3")
features = resnet(images, signature="image_feature_vector", as_dict=True)["resnet_v2_50/block4"]
flatten = tf.reshape(features, (-1, features.shape[3]))

假设我们要从 ResNet 的最后一个块中提取特征。

假设您想要获得中间输出,并在 tfhub 中为更新版本的 resnet 更新@gorjan 答案,您可以尝试这样的事情。


首先使用带有参数 return_endpoints=Truehub.KerasLayer 加载模型(这并非适用于所有模型,也没有记录在案,结果可能会有所不同):

hub_model_layer = hub.KerasLayer("https://tfhub.dev/google/imagenet/resnet_v2_50/feature_vector/5",
                                     trainable=True,  
                                     arguments=dict(return_endpoints=True))

然后你可以像这样编译一个模型:

input = tf.keras.layers.Input((244, 244, 3))
dict_output = hub_model_layer(input)

C2 = dict_output['resnet_v2_50/block1/unit_1/bottleneck_v2/shortcut']
C3 = dict_output['resnet_v2_50/block2/unit_1/bottleneck_v2/shortcut']
C4 = dict_output['resnet_v2_50/block3/unit_1/bottleneck_v2/shortcut']
C5 = dict_output['resnet_v2_50/block4/unit_1/bottleneck_v2/shortcut']

model = tf.keras.Model(inputs=input, outputs=[C2, C3, C4, C5])

变量dict_output是一个包含所有可用端点的字典,你可以打印它来搜索你想要使用的输出。它们没有按顺序排列,我也没有找到恢复图形的方法,但你可以通过层名称来猜测它们。