tensorflow基礎概念

flybywind發表於2017-12-01

Varibales

tensorflow的variable可以通過2種方式獲得:

w1 = tf.Variable(init_value, name = "w1", dtype = tf.float32)
w2 = tf.get_variable("w", initializer = initializer, shape = (2,3), dtype = tf.float32)

這兩種方式的區別是,w1是宣告變數,如果有重名的,則tf會自動給你編號。
w2則本質是從一個全域性dict裡取value的過程,它以name為key,去全域性dict中查詢指定的變數,如果有,則複用;沒有則通過initializer建立。

需要注意的是,複用變數需要通過如下方式顯式指定:

with tf.variable_scope("vs") as scope:
    w1 = tf.get_variable("w", shape = (2,3))
    scope.reuse_variables() # set reuse mode
    w2 = tf.get_variable("w", shape = (2,3))

另外,2種方式在使用name_scope和variable_scope時也有輕微不同:
tf.Variable總是會根據scope增加字首。但是tf.get_variable只會在variable_scope的時候增加字首

相關文章