TensorFlow程序一般可以分为两个阶段。在第一个阶段需要定义计算图中的所有的计算。第二个阶段为执行计算。
在TensorFlow程序中,系统会自动维护一个默认的计算图,通过tf.get_default_graph函数可以获取当前默认的计算图。
除去使用默认的计算图,TensorFlow支持通过tf.Graph函数生成新的计算图。不同计算图上的张量和运算都不会共享。以下代码示意了如何在不同计算图上定义和使用变量。
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(): #在计算图g2中定义变量"v",并设置初始值为1 v = tf.get_variable("v", initializer = tf.ones_initializer(shape = [1])) #在计算图g1中读取变量"v"的取值 with tf.Session(graph = g1) as sess: tf.initialize_all_variables().run() with tf.variable_scope("", reuse = True): #在计算图g1中,变量"v"的取值应该为0,所以下面这行会输出[0.] print(sess.run(tf.get_variable("v"))) #在计算图g2中读取变量“v”的取值 with tf.Session(graph = g2) as sess: tf.initialize_all_variables().run() with tf.variable_scope("", reuse = True): print(sess.run(tf.get_variable("v"))
原文:https://www.cnblogs.com/CZT-TS/p/11234993.html