tf. get_variable()
用于獲取一個變量,先搜索變量名,沒有就新建,有就直接用,并且不受name_scope的約束
遇到重名的變量創建且變量名沒有設置為共享變量時,則會報錯
tf.Variable()
每次都會新建變量
會自動檢測命名沖突并自行處理
name_scope
作用于操作:主要用于管理一個圖里面的各種op,返回的是一個以scope_name命名的context manager。一個graph會維護一個name_space的堆,每一個namespace下面可以定義各種op或者子namespace,實現一種層次化有條理的管理,避免各個op之間命名沖突。
variable_scope
可以通過設置reuse 標志以及初始化方式來影響域下的變量,一般與tf.name_scope()配合使用,用于管理一個graph中變量的名字,避免變量之間的命名沖突,tf.variable_scope(<scope_name>)允許在一個variable_scope下面共享變量。
import tensorflow as tf
with tf.name_scope('name_scope_x'):
var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
var3 = tf.Variable(name='var2', initial_value=[2], dtype=tf.float32)
var4 = tf.Variable(name='var2', initial_value=[2], dtype=tf.float32)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(var1.name, sess.run(var1))
print(var3.name, sess.run(var3))
print(var4.name, sess.run(var4))
# 輸出結果:
# var1:0 [-0.30036557] 可以看到前面不含有指定的'name_scope_x'
# name_scope_x/var2:0 [ 2.]
# name_scope_x/var2_1:0 [ 2.] 可以看到變量名自行變成了'var2_1',避免了和'var2'沖突
如果使用tf.get_variable()創建變量,且沒有設置共享變量,重名時會報錯
作者:C Li
鏈接:https://www.zhihu.com/question/54513728/answer/181819324
來源:知乎
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
import tensorflow as tf
with tf.name_scope('name_scope_1'):
var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
var2 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(var1.name, sess.run(var1))
print(var2.name, sess.run(var2))
# ValueError: Variable var1 already exists, disallowed. Did you mean
# to set reuse=True in VarScope? Originally defined at:
# var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
所以要共享變量,需要使用tf.variable_scope()
作者:C Li
鏈接:https://www.zhihu.com/question/54513728/answer/181819324
來源:知乎
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
import tensorflow as tf
with tf.variable_scope('variable_scope_y') as scope:
var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
scope.reuse_variables() # 設置共享變量
var1_reuse = tf.get_variable(name='var1')
var2 = tf.Variable(initial_value=[2.], name='var2', dtype=tf.float32)
var2_reuse = tf.Variable(initial_value=[2.], name='var2', dtype=tf.float32)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(var1.name, sess.run(var1))
print(var1_reuse.name, sess.run(var1_reuse))
print(var2.name, sess.run(var2))
print(var2_reuse.name, sess.run(var2_reuse))
# 輸出結果:
# variable_scope_y/var1:0 [-1.59682846]
# variable_scope_y/var1:0 [-1.59682846] 可以看到變量var1_reuse重復使用了var1
# variable_scope_y/var2:0 [ 2.]
# variable_scope_y/var2_1:0 [ 2.]
也可以這樣
with tf.variable_scope('foo') as foo_scope:
v = tf.get_variable('v', [1])
with tf.variable_scope('foo', reuse=True):
v1 = tf.get_variable('v')
assert v1 == v
或者這樣:
with tf.variable_scope('foo') as foo_scope:
v = tf.get_variable('v', [1])
with tf.variable_scope(foo_scope, reuse=True):
v1 = tf.get_variable('v')
assert v1 == v