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

问题描述

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

我现在想使用相同的 TensorFlow Hub 模块,但放弃提供的权重并使用我自己的内核初始化程序(例如 tf.initializers.truncated_normal、tf.initializers.he_normal 等)。

如何修改 TFHub 模块中的可训练变量以使用自定义初始化程序?为了清楚起见,我想在运行时替换预训练的权重,只保留模型架构。请让我知道我是否真的应该使用 TFSlim 或模型动物园。

这是我到目前为止所拥有的:

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()

这样做的正确方法是什么?

标签: pythontensorflowtensorflow-hub

解决方案


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

编辑 2019-04-15:另见tensorflow_hub 问题 #267:在 TF2 中,初始化程序的概念正在消失,因此 TF Hub 作者不想开始依赖它来获取 TF1 API。


推荐阅读