我以这种方式解决了这个问题:首先,我在图形“输出”中命名所需的计算,然后将此模型保存在下面的代码中…
import tensorflow as tf
x = tf.placeholder(dtype=tf.float64, shape=[], name="input")
a = tf.Variable(111, name="var1", dtype=tf.float64)
b = tf.Variable(-666, name="var2", dtype=tf.float64)
y = tf.add(x, a, name="output")
saver = tf.train.Saver()
with tf.Session() as sess:
tf.initialize_all_variables().run()
print(sess.run(y, Feed_dict={x: 555}))
save_path = saver.save(sess, "model.ckpt", Meta_graph_suffix='Meta', write_Meta_graph=True)
print("Model saved in file: %s" % save_path)
其次,我需要在图形中运行某些操作,我将其称为“输出”。因此,我只是用另一个代码还原模型,并通过使用名称为“ input”和“ output”的必要图形部分来运行还原的计算:
import tensorflow as tf
# Restore graph to another graph (and make it default graph) and variables
graph = tf.Graph()
with graph.as_default():
saver = tf.train.import_Meta_graph("model.ckpt.Meta")
y = graph.get_tensor_by_name("output:0")
x = graph.get_tensor_by_name("input:0")
with tf.Session() as sess:
saver.restore(sess, "model.ckpt")
print(sess.run(y, Feed_dict={x: 888}))
# Variable out:
for var in tf.all_variables():
print("%s %.2f" % (var.name, var.eval()))