如何修改 TensorFlow-Hub 模块中的可训练 tf.Variables 以使用自定义内核初始化程序?

How can I modify the trainable tf.Variables in a TensorFlow-Hub Module to use a custom kernel initializer?

我想从头开始训练 InceptionV3 神经网络。我已经有一个实现 运行,它利用这个 TensorFlow Hub 模块:https://tfhub.dev/google/imagenet/inception_v3/feature_vector/1 并利用包含的预训练权重执行微调。

我现在想使用 the same TensorFlow Hub module 但放弃提供的权重并使用我自己的内核初始化器(例如 tf.initializers.truncated_normal、tf.initializers.he_normal 等)。

如何修改 TFHub 模块中的可训练变量以使用自定义初始化程序?明确一点,我想在运行时替换预训练的权重,只保留模型架构。请让我知道我是否真的应该使用 TFslim 或 model zoo。

这是我目前的情况:

import tensorflow as tf
import tensorflow_hub as hub

tfhub_module_url = 'https://tfhub.dev/google/imagenet/inception_v3/feature_vector/1'
initializer = tf.truncated_normal

def main(_):
    _graph = tf.Graph()
    with _graph.as_default():
        module_spec = hub.load_module_spec(tfhub_module_url)
        height, width = hub.get_expected_image_size(module_spec)
        resized_input_tensor = tf.placeholder(tf.float32, [None, height, width, 3], name='resized_input_tensor')
        m = hub.Module(module_spec, trainable=True)
        bottleneck_tensor = m(resized_input_tensor)
        trainable_vars = tf.trainable_variables()
        # TODO: This fails, because this probably isn't how this is supposed to be done:
        for trainable_var in trainable_vars:
            trainable_var.initializer = tf.initializers.he_normal

    with tf.Session(graph=_graph) as sess:
        print(trainable_vars)


tf.logging.set_verbosity(tf.logging.INFO)
tf.app.run()

正确的做法是什么?

没有直接的方法可以做您想做的事,因为 TF Hub 模块实际上是为表示预训练的模型片段而构建的。如果你只想要图表,你可以直接使用 tensorflow_models/slim 代码。 (或者您可以修补 tensorflow_hub 库代码,使其首先不使用恢复操作重新连接变量初始值设定项。)

编辑 2019-04-15:另见 tensorflow_hub issue #267:在 TF2 中,初始化器的概念正在消失,因此 TF Hub 作者不想在 TF1 中依赖它开始 API.