tensorflow-新計算圖
阿新 • • 發佈:2018-12-15
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))