【tensorflow 學習】tf.get_variable()和tf.Variable()的區別

1. tf.Variable()

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

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

2.tf.get_variable()

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

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

3.區別

推薦使用tf.get_variable(), 因爲:

1. 初始化更方便

比如用xavier_initializer:

W = tf.get_variable("W", shape=[784, 256],
       initializer=tf.contrib.layers.xavier_initializer())

2. 方便共享變量

因爲tf.get_variable() 會檢查當前命名空間下是否存在同樣name的變量,可以方便共享變量。而tf.Variable 每次都會新建一個變量。

需要注意的是tf.get_variable() 要配合reusetf.variable_scope() 使用。


4. 舉個栗子

4.1 首先介紹一下tf.variable_scope().

如果已經存在的變量沒有設置爲共享變量,TensorFlow 運行到第二個擁有相同名字的變量的時候,就會報錯。爲了解決這個問題,TensorFlow 提出了 tf.variable_scope 函數:它的主要作用是,在一個作用域 scope 內共享一些變量,舉個簡單的栗子:

with tf.variable_scope("foo"):
    v = tf.get_variable("v", [1]) #v.name == "foo/v:0"

簡單來說就是給變量名前再加了個變量空間名。

4.2 對比

接下來看看怎麼用tf.get_variable()實現共享變量:

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.

然後看看如果用tf.Variable() 會有什麼效果:

with tf.variable_scope("two"):
    d = tf.get_variable("v", [1]) #d.name == "two/v:0"
    e = tf.Variable(1, name = "v", expected_shape = [1]) #e.name == "two/v_1:0"  

assert d==e #AssertionError: they are different objects

可以看到,同樣的命名空間(‘two’)和名字(v),但是d和e的值卻不一樣。

Reference:
1. https://stackoverflow.com/questions/37098546/difference-between-variable-and-get-variable-in-tensorflow
2. https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/variable_scope
3. http://blog.csdn.net/u013645510/article/details/53769689

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