[tf]中的name_scope和variable_scope以及变量重用的那些事

  • 特性:两个都会给tf.Variable创建的变量加上命名前缀,但是tf.name_scope不会给tf.get_varibale创建的变量加上命名前缀,tf.variable_scope会给tf.get_variable创建的变量加上命名前缀,这么做是与这两个方法的作用有关的。
  • name_scope的作用是为了在tensorboard中有折叠的层次化显示组件,不至于所有组件都糊在一起,比如我们有一个generator和一个discriminator那么就可以这样:
with tf.name_scope(name = 'generator') as vs:
    ...
  • variable_scope的所用是为保护和重用变量,比如我的模型中有两个LSTM,那么我就应该不同的LSTM设置不同的variable_scope这样dynamic_rnn内部的get_variable就能正确的区分两个LSTM的组件(因为dynamic_rnn内部的get_variablename都是一样的如果不使用variable_scope进行保护的话,重用都不知道重用哪一个了)。
    variable_scopereuse的几种方法
  • reuse的几种填写: None 表示查看上一层的当 reuse=tf.AUTO_REUSE 时,自动复用,如果变量存在则复用,不存在则创建。这是最安全的用法。
def foo():
  with tf.variable_scope("foo", reuse=tf.AUTO_REUSE):
    v = tf.get_variable("v", [1])
  return v

v1 = foo()  # Creates v.
v2 = foo()  # Gets the same, existing v.
assert v1 == v2
  • 因为创建过了一次,所以可以重用。
with tf.variable_scope("foo"):
    v = tf.get_variable("v", [1])
with tf.variable_scope("foo", reuse=True):
    v1 = tf.get_variable("v", [1])
assert v1 == v
  • 所以reuse不要一上来就设置成True,设置成tf.AUTO_REUSE是最靠谱的。
with tf.variable_scope("foo", reuse=True):
    v = tf.get_variable("v", [1])
    #  Raises ValueError("... v does not exists ...").

猜你喜欢

转载自blog.csdn.net/weixin_34343308/article/details/87337829