tensorflow计算与应用(1)-新计算图


A)tf.Graph.as_default()会创建一个新图,这个图成为当前线程的默认图。

B)在相同进程中创建多个计算图使用tf.Graph.as_default()。如果不创建新的计算图,默认的计算图将被自动创建。

C)如果创建一个新线程,想使用该线程的默认计算图,使用tf.Graph.as_default(),这个函数返回一个上下文管理器( context manager),它能够在这个上下文里面覆盖默认的计算图。在代码务必使用with。

# -*- coding: utf-8 -*-

"""

Spyder Editor

生成新的计算图,并完成常量初始化

[代码1]

[email protected]

"""

import tensorflow as tf

g = tf.Graph()

with g.as_default():

  c = tf.constant(5.0)

  assert c.graph is g

  print "ok"

[代码2]

# -*- coding: utf-8 -*-

"""

Spyder Editor

生成新的计算图,并完成常量初始化

[email protected]

"""

import tensorflow as tf

with tf.Graph().as_default() as g:

  c = tf.constant(5.0)

  assert c.graph is g

  print "ok"

[代码3]

# -*- coding: utf-8 -*-

"""

Spyder Editor

生成新的计算图,并完成常量初始化

[email protected]

"""

import tensorflow as tf

with tf.Graph().as_default() as g:

  c = tf.constant(5.0)

  assert c.graph is g

  print "ok"

sess=tf.Session(graph=g)

print sess.run(c)

sess.close()

[代码4]

# -*- coding: utf-8 -*-

"""

Spyder Editor

生成新的计算图,并完成常量初始化

[email protected]

"""

import tensorflow as tf

g=tf.get_default_graph()#默认计算图会自动注册

c = tf.constant(4.0)

result=c*c

assert result.graph is g#验证是否result操作属于g这个计算图

print "ok1"

with tf.Graph().as_default() as g1:

  c = tf.constant(5.0)

  assert c.graph is g1

  print "ok2"

  assert c.graph is g

  print "ok3"

sess=tf.Session(graph=g1)

print sess.run(c)

sess.close()

运行:

输出验证失败

ok1

ok2

....

assert c.graph is g

AssertionError

....

[代码5]

# -*- coding: utf-8 -*-

"""

Spyder Editor

生成新的计算图,并完成常量初始化,在新的计算 图中完成加法计算

[email protected]

"""

import tensorflow as tf

g1=tf.Graph()

with g1.as_default():

   value=[1.,2.,3.,4.,5.,6.]

   init = tf.constant_initializer(value)

   x=tf.get_variable("x",initializer=init,shape=[2,3])

   y=tf.get_variable("y",shape=[2,3],initializer=tf.ones_initializer())

   result=tf.add(x,y,name="myadd")

   

   assert result.graph is g1#验证是否result操作属于g1这个计算图

   print "ok"

with tf.Session(graph=g1) as sess:

   tf.global_variables_initializer().run()

   with tf.variable_scope("",reuse=True):

       print(sess.run(tf.get_variable("x")))

       print(sess.run(tf.get_variable("y")))

   print(sess.run(result))

猜你喜欢

转载自blog.csdn.net/u010255642/article/details/79946955