我正在尝试使用 tensorflow 进行研究,但我不明白如何打开和使用早期保存在文件中的 tf.Graph 类型的图表。像这样:
import tensorflow as tf
my_graph = tf.Graph()
with g.as_default():
x = tf.Variable(0)
b = tf.constant(-5)
k = tf.constant(2)
y = k*x + b
tf.train.write_graph(my_graph, '.', 'graph.pbtxt')
f = open('graph.pbtxt', "r")
# Do something with "f" to get my saved graph and use it below in
# tf.Session(graph=...) instead of dots
with tf.Session(graph=...) as sess:
tf.initialize_all_variables().run()
y1 = sess.run(y, feed_dict={x: 5})
y2 = sess.run(y, feed_dict={x: 10})
print(y1, y2)
最佳答案
您必须加载文件内容,将其解析为 GraphDef,然后导入。
它将被导入到当前图表中。你可能想用 graph.as_default():
上下文管理器来包装它。
import tensorflow as tf
from tensorflow.core.framework import graph_pb2 as gpb
from google.protobuf import text_format as pbtf
gdef = gpb.GraphDef()
with open('my-graph.pbtxt', 'r') as fh:
graph_str = fh.read()
pbtf.Parse(graph_str, gdef)
tf.import_graph_def(gdef)
关于python - 从文件打开 tensorflow 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40305996/