tensorflow中创建多个计算图(Graph)

tf程序中,系统会自动创建并维护一个默认的计算图,计算图可以理解为神经网络(Neural Network)结构的程序化描述。如果不显式指定所归属的计算图,则所有的tensor和Operation都是在默认计算图中定义的,使用tf.get_default_graph()函数可以获取当前默认的计算图句柄。

# -*- coding: utf-8 -*-)
import tensorflow as tf

a=tf.constant([1.0,2.0])
b=tf.constant([1.0,2.0])

result = a+b

print(a.graph is tf.get_default_graph()) # 输出为True,表示tensor a 是在默认的计算图中定义的
print(result.graph is tf.get_default_graph()) # 输出为True, 表示 Operation result 是在默认的计算图中定义的
print 'a.graph =        {0}'.format(a.graph)
print 'default graph =  {0}'.format(tf.get_default_graph())

输出:

True
True
a.graph =        <tensorflow.python.framework.ops.Graph object at 0x7f0480c9ca90>
default graph =  <tensorflow.python.framework.ops.Graph object at 0x7f0480c9ca90>

tf中可以定义多个计算图,不同计算图上的张量和运算是相互独立的,不会共享。计算图可以用来隔离张量和计算,同时提供了管理张量和计算的机制。计算图可以通过Graph.device函数来指定运行计算的设备,为TensorFlow充分利用GPU/CPU提供了机制。

  1. 使用 g = tf.Graph()函数创建新的计算图;
  2. 在with g.as_default():语句下定义属于计算图g的张量和操作
  3. 在with tf.Session()中通过参数 graph = xxx指定当前会话所运行的计算图;
  4. 如果没有显式指定张量和操作所属的计算图,则这些张量和操作属于默认计算图;
  5. 一个图可以在多个sess中运行,一个sess也能运行多个图


创建多个计算图:

# -*- 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

  • 4
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值