g1.version

tf程序中,系统会自动创建并维护一个默认的计算图,计算图可以理解为神经网络(Neural Network)结构的程序化描述。如果不显式指定所归属的计算图,则所有的tensor和Operation都是在默认计算图中定义的,使用tf.get_default_graph()函数可以获取当前默认的计算图句柄。

  1. # -*- coding: utf-8 -*-)
  2. import tensorflow as tf
  3. a=tf.constant([ 1.0, 2.0])
  4. b=tf.constant([ 1.0, 2.0])
  5. result = a+b
  6. print(a.graph is tf.get_default_graph()) # 输出为True,表示tensor a 是在默认的计算图中定义的
  7. print(result.graph is tf.get_default_graph()) # 输出为True, 表示 Operation result 是在默认的计算图中定义的
  8. print 'a.graph = {0}'.format(a.graph)
  9. print 'default graph = {0}'.format(tf.get_default_graph())

输出:
  1. True
  2. True
  3. a.graph = <tensorflow.python.framework.ops.Graph object at 0x7f0480c9ca90>
  4. default graph = <tensorflow.python.framework.ops.Graph object at 0x7f0480c9ca90>

tf中可以定义多个计算图,不同计算图上的张量和运算是相互独立的,不会共享。计算图可以用来隔离张量和计算,同时提供了管理张量和计算的机制。计算图可以通过Graph.device函数来指定运行计算的设备,为TensorFlow充分利用GPU/CPU提供了机制。

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


创建多个计算图:
  1. # -*- coding: utf-8 -*-)
  2. import tensorflow as tf
  3. # 在系统默认计算图上创建张量和操作
  4. a=tf.constant([ 1.0, 2.0])
  5. b=tf.constant([ 2.0, 1.0])
  6. result = a+b
  7. # 定义两个计算图
  8. g1=tf.Graph()
  9. g2=tf.Graph()
  10. # 在计算图g1中定义张量和操作
  11. with g1.as_default():
  12. a = tf.constant([ 1.0, 1.0])
  13. b = tf.constant([ 1.0, 1.0])
  14. result1 = a + b
  15. with g2.as_default():
  16. a = tf.constant([ 2.0, 2.0])
  17. b = tf.constant([ 2.0, 2.0])
  18. result2 = a + b
  19. # 在g1计算图上创建会话
  20. with tf.Session(graph=g1) as sess:
  21. out = sess.run(result1)
  22. print 'with graph g1, result: {0}'.format(out)
  23. with tf.Session(graph=g2) as sess:
  24. out = sess.run(result2)
  25. print 'with graph g2, result: {0}'.format(out)
  26. # 在默认计算图上创建会话
  27. with tf.Session(graph=tf.get_default_graph()) as sess:
  28. out = sess.run(result)
  29. print 'with graph default, result: {0}'.format(out)
  30. print g1.version # 返回计算图中操作的个数

输出:

  1. with graph g1, result: [ 2. 2.]
  2. with graph g2, result: [ 4. 4.]
  3. with graph default, result: [ 3. 3.]
  4. 3

猜你喜欢

转载自blog.csdn.net/qq_31442743/article/details/80915689
G 1