tf.Variable()、tf.get_variable()

- 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可以用各種初始化方法,不用明確指定值。

- 區別

[1]. tf.get_variable()可以實現共享變量,而tf.Variable()只能新建變量。
[2]. get_variable新建變量如果遇見重複的name則會因爲重複而報錯(在沒有啓動reuse=True的情況下)。
[3]. variable新建的變量如果遇見重複的name則會自動修改前綴,以避免重複出現。


- 代碼演示

  • 實現共享
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的變量
  • Variable()
import tensorflow as tf

with tf.name_scope('nameScope'):
    n1 = tf.Variable(1,name= "1")

with tf.name_scope("nameScope"):
    n2 = tf.Variable(3,name="1")

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(n1)# <tf.Variable 'nameScope/1:0' shape=() dtype=int32_ref>
    print(n2)# <tf.Variable 'nameScope_1/1:0' shape=() dtype=int32_ref>
    # tf.Variable會自動檢修改前綴以避免重複出現

參考

https://blog.csdn.net/timothytt/article/details/79789274
https://blog.csdn.net/NNNNNNNNNNNNY/article/details/70177509

記錄時間

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