如何在不初始化变量的情况下保存张量流图?

时间:2019-06-24 03:41:35

标签: python tensorflow

我遇到的问题可以反映为:

tf.reset_default_graph()

x = tf.placeholder(dtype=tf.int32, shape=())
init = tf.zeros(shape=tf.squeeze(x), dtype=tf.float32)

v = tf.get_variable('foo', initializer=init, validate_shape=False)


v_sig = tf.saved_model.signature_def_utils.build_signature_def(
            inputs={"x_input": tf.saved_model.utils.build_tensor_info(x)},
            outputs={
                'v_output': tf.saved_model.utils.build_tensor_info(v)
            },
            method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME
)

with tf.Session() as sess:
    builder = tf.saved_model.builder.SavedModelBuilder(export_dir="~/test/")
    sess.run(tf.global_variables_initializer())  # here leads to problem
    builder.add_meta_graph_and_variables(
        sess, [tf.saved_model.tag_constants.SERVING],
        signature_def_map={
            'v_sig': v_sig
        },
        main_op=tf.tables_initializer(),
        strip_default_attrs=True
    )
    builder.save()

我有一个变量foo,它的形状是动态计算的(取决于占位符x的输入)。当我尝试将其另存为图形时,遇到错误:

  

您必须使用dtype int32输入占位符张量“占位符”的值

如果我不运行global_variables_initializer,它将出现错误variable does not exists

那该如何解决呢?我已经坚持了很长时间,感谢您的回答。

1 个答案:

答案 0 :(得分:0)

您可以将图形另存为元图对象,而无需初始化变量,如下所示:

import tensorflow as tf
import json

x = tf.placeholder(dtype=tf.int32, shape=(), name='x')
init = tf.zeros(shape=tf.squeeze(x), dtype=tf.float32, name='init')
v = tf.get_variable('foo', initializer=init, validate_shape=False)
tensor_names = {
    'x': x.name,
    'v': v.name
}
with open('tensor_names.json', 'w') as fo:
  json.dump(tensor_names, fo)

fname = 'graph.meta'
proto = tf.train.export_meta_graph(filename=fname,
                                   graph=tf.get_default_graph())

然后恢复此图:

import tensorflow as tf
import json

with open('tensor_names.json', 'r') as fo:
  tensor_names = json.load(fo)

graph = tf.Graph()
with graph.as_default():
  tf.train.import_meta_graph(fname)
  x = graph.get_tensor_by_name(tensor_names['x'])
  v = graph.get_tensor_by_name(tensor_names['v'])

# works as expected: 
with tf.Session(graph=graph) as sess:
  sess.run(tf.global_variables_initializer(), {x:5})
  print(v.eval()) # [0. 0. 0. 0. 0.]