Tensorflow 2集线器:如何获取中间层的输出?

时间:2019-08-08 10:16:35

标签: tensorflow tensorflow-hub

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

是否可以通过tf-hub查看加载的模块的层? 谢谢


更新

不幸的是,resnet无法用于tf2-hub,因此我决定使用resent的内置keras实现,至少要等到有集线器暗示时才能使用。

这是我如何使用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)

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作来检查中间输出:

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)

然后,如果要将集线器模块的中间层链接到图形的其余部分,则可以执行以下操作:

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的最后一块提取特征。