代码中有时候会遇到
with tf.Graph().as_default():
其实这个可以有也可以没有,可能是可以让自己的思路更加清楚吧,知道这里开始新建图了。
tensorflow官方教程
翻译
简介
当我们训练一个模型时,通常的做法是用一个 Graph 训练模型,然后用另一个 Graph 来评估模型的训练情况,因为在许多情况下,训练和测试的前向推导过程是不一样的,因为训练的时候通常包括了dropout和 BN 操作,而测试的时候则不需要或使用不一样的参数。但是这样有一个使用起来很不方便的地方,那就是训练和测试各自需要一个显卡,对于资源不是那么充裕的使用者就很不方便了,是否可以在一个进程内运行两个不同的计算图呢?
创建新计算图的优势
通常情况下,使用 TensorFlow 提供的默认计算图 Graph 就已经能够完成所有的工作了,但是,它也提供了方法来操作默认的计算图 Graph,用以适应更复杂的情况,比如说一个 Graph 定义了它内部所有 OP 的命名空间,所有内部 OP 都会自动命名为不重复的情况,但是还是会使得 OP 的名称比较复杂,那么如果显式的创建一个 Graph 就会给你为 OP 命名带来更多的控制权。
另外,默认的计算图 Graph 会存储所有的 OP 和 tensor 的信息,但是如果你创建的计算图是多个没有关联的子计算图,那么还不如创建多个独立的计算图,这样会使得原来的不相干的子图之间的声明被系统当做垃圾回收。
使用方法(有点问题)
可以先使用 tf.Graph 建立一个新的计算图,然后使用 tf.Graph.as_default 来创建一个上下文管理器来指定该计算图内部的结构;可以看如下代码:
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
这段代码表明了两种使用不同的 session 来运行不同的计算图的方式,一种是直接在该计算图g_1 Graph 内部调用 session ,一种是在该计算图的外部将 g_2 传入 session。
如果要查看当前使用的是哪个计算图,可以使用如下方法:
# Print all of the operations in the default graph.
g = tf.get_default_graph()
print(g.get_operations())
这段代码运行出来,在这记录一下。
使用方法
参考
我觉得参考的代码看起来很舒服,简单的变成的py3,代码很清晰,比官网好多了。
# -*- coding: utf-8 -*-)
import tensorflow as tf
# 在系统默认计算图上创建张量和操作
a=tf.constant([1.0,2.0])
b=tf.constant([2.0,1.0])
result = a+b
# 定义两个计算图
g1=tf.Graph()
g2=tf.Graph()
# 在计算图g1中定义张量和操作
with g1.as_default():
a = tf.constant([1.0, 1.0])
b = tf.constant([1.0, 1.0])
result1 = a + b
with g2.as_default():
a = tf.constant([2.0, 2.0])
b = tf.constant([2.0, 2.0])
result2 = a + b
# 在g1计算图上创建会话
with tf.Session(graph=g1) as sess:
out = sess.run(result1)
print('with graph g1, result: {0}'.format(out))
with tf.Session(graph=g2) as sess:
out = sess.run(result2)
print('with graph g2, result: {0}'.format(out))
# 在默认计算图上创建会话
with tf.Session(graph=tf.get_default_graph()) as sess:
out = sess.run(result)
print( 'with graph default, result: {0}'.format(out))
print(g1.version) # 返回计算图中操作的个数
结果
-
with graph g1, result: [2. 2.]
with graph g2, result: [4. 4.]
with graph default, result: [3. 3.]
3