TensorFlow计算模型-计算图

TensorFlow中的所有计算都会被转化为计算图上的节点,每一个节点都是一个运算。不同计算图上的张量(可以简单的被理解为多维数组)和运算都不会共享,以下代码示意了如何在不同计算图上定义和使用变量。

import tensorflow as tf

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

g2 = tf.Graph()
with g2.as_default():   #此时将g2设为默认图
    # 在计算图个g2中定义变量"v",并设置初始值为1
    v = tf.get_variable("v", initializer=tf.ones_initializer()(shape=[1]))

#在计算图g1找那个读取变量"v"的取值
with tf.Session(graph=g1) as sess:
    tf.global_variables_initializer().run() #初始化
    with tf.variable_scope("", reuse=True):  #设置图g1中v为共享变量,共享变量域名为空,定义过v后reuse才能为True
        #在计算图g1中,变量"v"的取值应该为0,所以会输出[0.]
        print(sess.run(tf.get_variable("v")))   #返回v的值

#在计算图g2找那个读取变量"v"的取值
with tf.Session(graph=g2) as sess:
    tf.global_variables_initializer().run() #初始化
    with tf.variable_scope("", reuse=True):  #设置图g2中v为共享变量,共享变量域名为空,定义过v后reuse才能为True
        #在计算图g2中,变量"v"的取值应该为0,所以会输出[1.]
        print(sess.run(tf.get_variable("v")))   #返回v的值

>>[ 0.]
  [ 1.]

可以看出运行不同计算图时,变量v的值也是不一样的。

你可能感兴趣的:(TensorFlow)