130、TensorFlow操作多个计算图

# Programming with multiple graphs
# 当训练一个模型的时候一个常用的方式就是使用一个图来训练你的模型
# 另一个图来评价和计算训练的效果
# 在许多情况下前向计算和训练是不同的
# 例如像Dropout和batch正则化使用不同的操作在不同的Case条件下
# 更进一步地说 通过使用默认的工具类,如tf.train.Saver使用tf.Variable的命名空间
# 在保存检查点的时候tf.Variable的名字是根据tf.Operation来定义
# 当你使用这种方法来编程的时候你或者使用独立的Python进程来建立和执行这个计算图
# 或者你可以使用多个计算图在相同的进程中
# tf.Graph为tf.Operation定义了命名空间
# 每一个操作必须有唯一的名字
# TensorFlow会通过在操作名字后面appending上_1,_2
# 如果所起的名字已经存在了,使用多个计算图能够让你更好地控制每个计算节点

# 默认的图存储信息关于每个tf.Operation和tf.Tensor
# 如果你对程序创建了更大数量的没有被连接的子图
# 使用多个计算图或许是更有效果的。因此, 不相关的状态可以被垃圾收集
import tensorflow as tf
g_1 = tf.Graph()
with g_1.as_default():
    # Operations created in this scope will be added to 'g_1'
    c = tf.constant("Node in g_1")
    
    # Sessions created in this scope will run operations from 'g_1'
    sess_1 = tf.Session()
g_2 = tf.Graph()
with g_2.as_default():
    # operations created in this scope will be added to 'g_2'
    d = tf.constant("Node in g_2")

# Alternatively , you can pass a graph when constructing a 'tf.Session'
# 'sess_2' will run operations from 'g_2'
sess_2 = tf.Session(graph=g_2)
assert c.graph is g_1
assert sess_1.graph is g_1

assert d.graph is g_2
assert sess_2.graph is g_2

 

posted @ 2018-02-17 11:21  香港胖仔  阅读(1569)  评论(0编辑  收藏  举报