<p>使用<code>main_op</code>或<code>legacy_init_op</code>kwarg将元图添加到具有<a href="https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/saved_model/builder/SavedModelBuilder#add_meta_graph" rel="noreferrer">^{<cd1>}</a>的SavedModel包时,可以指定“初始化”操作。如果需要多个操作,可以使用单个操作,也可以使用<code>tf.group</code>将多个操作组合在一起。</p>
<p>注意,在Cloud ML引擎中,必须使用<code>legacy_init_op</code>。但是在未来的<code>runtime_version</code>中,您将能够使用<code>main_op</code>
(IIRC,从<code>runtime_version == 1.2</code>开始)</p>
<p>saved_model模块提供了一个内置的<a href="https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/saved_model/main_op/main_op" rel="noreferrer">^{<cd9>}</a>,用于在单个op(本地变量初始化和表初始化)中结束公共初始化操作。</p>
<p>总之,代码应该是这样的(改编自<a href="https://github.com/GoogleCloudPlatform/cloudml-samples/blob/master/census/tensorflowcore/trainer/task.py#L321" rel="noreferrer">this example</a>):</p>
<pre><code> 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()
)
</code></pre>
<p>注意:如果您使用的是高级库(如<a href="https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/estimator" rel="noreferrer">^{<cd10>}</a>),这应该是默认的,如果需要指定其他初始化操作,可以将它们指定为传递给模型中<a href="https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/estimator/EstimatorSpec" rel="noreferrer">^{<cd12>}</a>的<a href="https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/train/Scaffold" rel="noreferrer">^{<cd11>}</a>对象的一部分fn。</p>