tensorflow:计算图

#以下代码会自动生成一个计算图,且为默认计算图
import tensorflow as tf
a = tf.constant([1.0, 2.0],name = "a")
b = tf.constant([2.0, 3.0],name = "b")
result = a + b
#a的所属计算图是默认计算图
print(a.graph is tf.get_default_graph())
#True
输出结果:

tensorflow:计算图_第1张图片

新建一个计算图:使用tf.Graph()

#coding:utf-8
import tensorflow as tf

g1 = tf.Graph()
with g1.as_default():
    # 在图g1中定义初始变量v, 并设置初始值为0
    v = tf.get_variable("v", initializer = tf.zeros_initializer(shape=[1]))

g2 = tf.Graph()
with g2.as_default():
    # 在图g1中定义初始变量v, 并设置初始值为1
    v = tf.get_variable("v",shape=[1],  initializer=tf.ones_initializer(dtype=tf.float32))


with tf.Session(graph=g1) as sess:
    sess.run(tf.global_variables_initializer())
    with tf.variable_scope('', reuse=True):
        # 输出值为0
        print (sess.run(tf.get_variable("v")))



with tf.Session(graph = g2) as sess:
    sess.run(tf.global_variables_initializer())
    with tf.variable_scope('', reuse=True):
       # 输出值为1
       print (sess.run(tf.get_variable('v')))

输出:

tensorflow:计算图_第2张图片

你可能感兴趣的:(深度学习)