創(chuàng)建圖對象
import tensorflow as tf
import numpy as np
a = tf.constant(123)
print(a.graph)
print(tf.get_default_graph())
<tensorflow.python.framework.ops.Graph object at 0x7f46885216d8>
<tensorflow.python.framework.ops.Graph object at 0x7f46885216d8>
當(dāng)tensorflow庫被加載時革答,即使用戶沒有顯示地創(chuàng)建一個圖,他也會自動創(chuàng)建一個圖對象,并將其作為默認(rèn)的額數(shù)據(jù)流圖。
創(chuàng)建顯示圖
import tensorflow as tf
import numpy as np
g= tf.Graph() #創(chuàng)建了一個圖對象g
with g.as_default(): # 將g設(shè)置為默認(rèn)圖像
a = tf.constant(123)
print(a.graph)
print(tf.get_default_graph())
<tensorflow.python.framework.ops.Graph object at 0x7f466363b2e8>
<tensorflow.python.framework.ops.Graph object at 0x7f466363b2e8>
as_default()
:返回一個上下文管理器示损,使得當(dāng)前圖對象稱為當(dāng)前默認(rèn)圖對象;在一個進程中創(chuàng)建多個人圖對象時(圖對象互不依賴)嚷硫,非常有用检访。
get_default_graph()
:獲取當(dāng)前圖對象的句柄(某個事務(wù)的唯一標(biāo)識)。
創(chuàng)建多個圖
import tensorflow as tf
import numpy as np
g1 = tf.Graph()
g2 = tf.Graph()
with g1.as_default():
a = tf.constant(123)
print(a.graph)
print(tf.get_default_graph())
with g2.as_default():
b = tf.multiply(2, 3)
print(b.graph)
print(tf.get_default_graph())
<tensorflow.python.framework.ops.Graph object at 0x7f466363b630>
<tensorflow.python.framework.ops.Graph object at 0x7f466363b630>
<tensorflow.python.framework.ops.Graph object at 0x7f4688609b00>
<tensorflow.python.framework.ops.Graph object at 0x7f4688609b00>
Tensor 對象 a 和 b 所屬的圖已不再一樣仔掸,隨著as_default()
的值變化而變化脆贵。