tensorflow中Graph图
在tensorflow的编程思想说到,在tensorflow程序中应包含两个部分:一个是构建计算图的部分,另一个是把建好的计算图放在一个Sesstion会话中的执行部分。 这篇主要讲使用tf.Graph()
函数创建一个新的计算图的方法。
1. 只创建一个Graph图
在Tensorflow中,始终存在一个默认的Graph,当你创建Operation、Tensor时,tensorflow会将你这些节点和边自动添加到这个默认Graph中。
那么,当你只想创建一个图时,并不需要使用tf.Graph()
函数创建一个新图,而是直接定义需要的Tensor和Operation,这样,tensorflow会将这些节点和边自动添加到默认Graph中。
import tensorflow as tf
###-----图的构建阶段---------###
w = tf.Variable([[3.0,2.5],[1.0,2.7]]) #图中边Variabel的定义
x = tf.constant(1.0,shape=[1,2]) #图中边x_tensor的生成
y = tf.matmul(w,tf.transpose(x)) #节点:变量的乘法和转置操作(operation)
init_op = tf.global_variables_initializer() #节点:Variable的initialize_operation
#----------tensorflow会将上面定义的节点和边自动添加到默认Graph中------#
###------图的执行阶段-------###
with tf.Session() as sess:
sess.run(init_op) # 执行init_op操作,此时tf.matmul并没有run
print(sess.run(y)) # 在会话中执行tf.matmul操作, 打印y_tensor,
2. 定义多个Graph图
在tensorflow中,可以使用tf.Graph()
函数创建图。如果我们需要定义多个Graph,则可以在with语句中调用tf.Graph.as_default()方法
将某个graph设置成默认Graph,这样with语句块中调用的Operation或Tensor将会添加到该Graph中。
with语句是保证操作的资源可以正确的打开和释放,而且不同的计算图上的张量和运算彼此分离,互不干扰.
import tensorflow as tf
graph1 = tf.Graph()
with graph1.as_default():#创建图1
c1 = tf.constant([9.0])
with tf.Graph().as_default() as graph2: #创建图2
c2 = tf.constant([1.0])
with tf.Session(graph=graph1) as sess1:#使用sess1 运行graph1
print (sess1.run(c1))
with tf.Session(graph=graph2) as sess2:#使用sess2 运行graph2
print (sess2.run(c2))
注:
定义多个图时,可以通过设置tf.Sesstion(graph=)
中的参数,选择当前的Session执行哪个计算图。
3 指定Graph计算图运行的设备
TensorFlow中计算图可以通过tf.Graph.device
函数来指定运行计算图的设备。下面程序将加法计算放在CPU上执行,也可以使用tf.device
达到同样的效果。
g = tf.Graph()
with g.device('/cpu:0'):
result = 1 + 2