1. 程式人生 > >tf.Variable()、tf.get_variable()、tf.name_scope()、tf.variable_scope()

tf.Variable()、tf.get_variable()、tf.name_scope()、tf.variable_scope()

- tf.Variable()

W = tf.Variable(<initial-value>, name=<optional-name>)

用於生成一個初始值為initial-value的變數。必須指定初始化值

-tf.get_variable()

W = tf.get_variable(name, shape=None, dtype=tf.float32, initializer=None,
       regularizer=None, trainable=True, collections=None)

獲取已存在的變數(要求不僅名字,而且初始化方法等各個引數都一樣),如果不存在,就新建一個。 initializer可以用各種初始化方法,不用明確指定值。

- 區別

tf.get_variable()可以實現共享變數,而tf.Variable()只能新建變數。 需要注意的是tf.get_variable() 要配合reuse和tf.variable_scope() 使用。

- 程式碼演示

  • tf.variable_scope()
with tf.variable_scope("foo"):
    v = tf.get_variable("v", [1]) #v.name == "foo/v:0"
    # variable_scope()會給Variable或者get_variable()建立的變數的名字新增上字首foo
  • 實現共享
with tf.variable_scope("one"):
    a = tf.get_variable("v", [1]) #a.name == "one/v:0"
with tf.variable_scope("one"):
    b = tf.get_variable("v", [1]) #建立兩個名字一樣的變數會報錯 ValueError: Variable one/v already exists 
with tf.variable_scope("one", reuse = True): #注意reuse的作用。
    c = tf.get_variable("v"
, [1]) #c.name == "one/v:0" 成功共享,因為設定了reuse assert a==c #Assertion is true, they refer to the same object. # 注意,如果開啟了reuse = True # 那麼就必須複用變數,如果指定的變數名不存在,則會報錯 with tf.variable_scope("one", reuse = True): #注意reuse的作用。 d = tf.get_variable("p", [1]) #c.name == "one/v:0" 報錯,因為之前沒有name為p的變數

參考

記錄時間

2018/9/13 13:15 第一次