標籤:inf 範圍 共用 作用 pre style 建立 == flow
變數範圍
tensorflow提供了變數範圍和共用變數這樣的概念,有幾個重要的作用。
變數範圍域
通過tf.variable_scope(<scope_name>)建立指定名字的變數範圍
with tf.variable_scope("itcast") as scope: print("----")
加上with語句就可以在整個itcast變數範圍下就行操作。
嵌套使用
變數範圍可以嵌套使用
with tf.variable_scope("itcast") as itcast: with tf.variable_scope("python") as python: print("----")變數範圍下的變數
在同一個變數範圍下,如果定義了兩個相同名稱的變數(這裡先用tf.Variable())會怎麼樣呢?
with tf.variable_scope("itcast") as scope: a = tf.Variable([1.0,2.0],name="a") b = tf.Variable([2.0,3.0],name="a")
我們通過tensoflow提供的計算圖介面觀察
我們發現取了同樣的名字,其實tensorflow並沒有當作同一個,而是另外又增加了一個a_1,來表示b的圖
變數範圍
當每次在一個變數範圍中建立變數的時候,會在變數的name前面加上變數範圍的名稱
with tf.variable_scope("itcast"): a = tf.Variable(1.0,name="a") b = tf.get_variable("b", [1]) print(a.name,b.name)
得道結果
(u‘itcast/a:0‘, u‘itcast/b:0‘)
對於嵌套的變數範圍來說
with tf.variable_scope("itcast"): with tf.variable_scope("python"): python3 = tf.get_variable("python3", [1])assert python3.name == "itcast/python/python3:0"var2 = tf.get_variable("var",[3,4],initializer=tf.constant_initializer(0.0))
TensorFlow進階(四)---名稱域和共用變數