【TensorFlow學習筆記(一)】變量作用域

  • 更新時間:2019-06-02
    TensorFlow中有兩個作用域,一個是name_scope,一個是variable_scopename_scope主要是給op_name加前綴,variable_scope主要是給variable_name加前綴。

variable_scope

variable_scope變量作用域機制主要由兩部分組成:

v = tf.get_variable_scope(name, shape, dtype, initializer) # 根據名字返回變量
tf.variable_scope(<scope_name>) # 爲變量指定命名空間

共享變量:

# 創建變量作用域
with tf.variable_scope("foo") as scope:
    v = tf.get_variable("v", [1])
# 設置reuse參數爲True時,共享變量。reuse的默認值爲False。
with tf.variable_scope("foo", reuse=True):
    v1 = tf.get_variable("v", [1])
assert v1 == v

獲取變量作用域

通過tf.variable_scope()獲取變量作用域:

with tf.variable_scope("foo") as foo_scope:
    v = tf.get_variable("v", [1])
with tf.variable_scope(foo_scope):
    w = tf.get_variable("w", [1])

變量作用域的初始化

變量作用域默認攜帶一個初始化器,在這個作用域中的子作用域或變量都可以繼承或重寫父作用域初始化器中的值。

with tf.variable_scope("foo", initializer=tf.constant_initializer(0.4)):
    v = tf.get_variable("v", [1])
    assert v.eval() == 0.4 # 被作用域初始化
    w = tf.get_variable("w", [1], initializer=tf.constant_initializer(0.3)):
        assert w.eval() == 0.3 # 重寫初始化器的值
    with tf.variable_scope("bar"):
        v = tf.get_variable("v", [1])
        assert v.eval() == 0.4 # 繼承默認的初始化器
    with tf.variable_scope("baz", initializer=tf.tf.constant_initializer(0.2)):
        v = tf.get_variable("v", [1])
        assert v.eval() == 0.2 # 重寫父作用域的初始化器的值

name_scope

name_scope爲變量劃分範圍,在可視化中,表示在計算圖中的一個層級。name_scope會影響op_name,不會影響get_variable()創建的變量,而會影響通過Variable()創建的變量。

with tf.variable_scope("foo"):
    with tf.name_scope("bar"):
        v = tf.get_variable("v", [1])
        b = tf.Variable(tf.zeros([1]), name='b')
        x = 1.0 +v
assert v.name == "foo/v:0"
assert b.name == "foo/bar/b:0"
assert x.op.name == "foo/bar/add"

tf.name_scope()返回一個字符串。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章