【tensorflow】如何使用多个计算图(Graph)

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

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)  # 返回计算图中操作的个数

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zhouzongzong/article/details/94429323