如何保持查找表的初始化以进行预测(而不仅仅是训练)?

How to keep lookup tables initialized for prediction (and not just training)?

我使用训练数据(作为输入)从 tf.contrib.lookup 创建了一个查找 table。然后,我通过该查找传递每个输入 table,然后再通过我的模型传递它。

这适用于训练,但是当从同一模型进行在线预测时,它会引发错误:

Table not initialized

我正在使用 SavedModel 来保存模型。我 运行 来自这个已保存模型的预测。

如何初始化此 table 以使其保持初始化状态?或者是否有更好的方法来保存模型,以便 table 始终被初始化?

当您使用 tf.saved_model.builder.SavedModelBuilder.add_meta_graph 将元图添加到您的 SavedModel 包时,您可以指定一个 "initialization" 操作,使用 main_oplegacy_init_op kwarg。您可以使用单个操作,或者如果您需要多个操作,则可以使用 tf.group 将多个操作组合在一起。

请注意,在 Cloud ML Engine 中,您必须使用 legacy_init_op。但是在以后的 runtime_version 中,您将可以使用 main_op (IIRC,以 runtime_version == 1.2 开头)

saved_model 模块提供了一个内置的 tf.saved_model.main_op.main_op 来将常见的初始化操作包装在单个操作中(局部变量初始化和 table 初始化)。

所以总而言之,代码应该如下所示(改编自 this example):

  exporter = tf.saved_model.builder.SavedModelBuilder(
      os.path.join(job_dir, 'export', name))

  # signature_def gets constructed here

  with tf.Session(graph=prediction_graph) as session:
    # Need to be initialized before saved variables are restored
    session.run([tf.local_variables_initializer(), tf.tables_initializer()])
    # Restore the value of the saved variables
    saver.restore(session, latest)
    exporter.add_meta_graph_and_variables(
        session,
        tags=[tf.saved_model.tag_constants.SERVING],
        signature_def_map={
            tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature_def
        },
        # Relevant change to the linked example is here!
        legacy_init_op=tf.saved_model.main_op.main_op()
    )

注意:如果您使用的是高级库(例如 model_fn 中的 tf.estimator) this should be the default, and if you need to specify additional initialization actions you can specify them as part of the tf.train.Scaffold object that you pass to your tf.estimator.EstimatorSpec

我认为你最好使用 tf.tables_initializer() 作为 legacy_init_op

除了 table 初始化之外,

tf.saved_model.main_op.main_op() 还添加了局部和全局初始化操作。 当您加载保存的模型并运行 legacy_init_op 时,它会重置您的变量,这不是您想要的。