[英]Gradually building tf.Graph and executing it
我正在尝试根据某些条件逐步构建tf.Graph
,并在完成附加操作后运行一次。
该代码如下所示:
class Model:
def __init__(self):
self.graph = tf.Graph()
... some code ...
def build_initial_graph(self):
with self.graph.as_default():
X = tf.placeholder(tf.float32, shape=some_shape)
... some code ...
def add_to_existing_graph(self):
with self.graph.as_default():
... some code adding more ops to the graph ...
def transform(self, data):
with tf.Session(graph=self.graph) as session:
y = session.run(Y, feed_dict={X: data})
return y
调用方法看起来像这样
model = Model()
model.build_initial_graph()
model.add_to_existing_graph()
model.add_to_existing_graph()
result = model.transform(data)
所以,两个问题
feed_dict
X
,什么是正确的方法? 问题1:这当然是建立模型的合法方法,但更多的是见解。 我只建议将张量存储为属性(请参阅问题2的答案) self.X=...
您可以看一下关于如何以面向对象的方式构造TensorFlow模型的非常不错的文章 。
问题2 :原因确实很简单,并且取决于变量X
不在您的transform
方法的范围内。
如果您执行以下操作,一切都会正常:
def build_initial_graph(self):
with self.graph.as_default():
self.X = tf.placeholder(tf.float32, shape=some_shape)
... some code ...
def transform(self, data):
with tf.Session(graph=self.graph) as session:
return session.run(self.Y, feed_dict={self.X: data})
更详细地讲,在TensorFlow中,您定义的所有张量或操作(例如tf.placeholder
或tf.matmul
)都在要处理的tf.Graph()
中定义re working on. You might want to store them in Python variable, as you did by doing
re working on. You might want to store them in Python variable, as you did by doing
X = tf.placeholder`一样,但这不是强制性的。
如果要访问定义的张量之一,则可以
X
不在方法范围内,这是您的尝试),或 tf.get_variable
方法直接从图形中检索它们(您需要知道它的名称)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.