如何在没有默认创建新范围的情况下在tensorflow中重用变量范围?

Dav*_*rks 7 python machine-learning deep-learning tensorflow tensor

我在图的一部分中创建了一个变量作用域,稍后在图的另一部分中我想将OP添加到现有作用域.这相当于这个蒸馏的例子:

import tensorflow as tf

with tf.variable_scope('myscope'):
  tf.Variable(1.0, name='var1')

with tf.variable_scope('myscope', reuse=True):
  tf.Variable(2.0, name='var2')

print([n.name for n in tf.get_default_graph().as_graph_def().node])
Run Code Online (Sandbox Code Playgroud)

产量:

['myscope/var1/initial_value', 
 'myscope/var1', 
 'myscope/var1/Assign', 
 'myscope/var1/read', 
 'myscope_1/var2/initial_value', 
 'myscope_1/var2', 
 'myscope_1/var2/Assign', 
 'myscope_1/var2/read']
Run Code Online (Sandbox Code Playgroud)

我想要的结果是:

['myscope/var1/initial_value', 
 'myscope/var1', 
 'myscope/var1/Assign', 
 'myscope/var1/read', 
 'myscope/var2/initial_value', 
 'myscope/var2', 
 'myscope/var2/Assign', 
 'myscope/var2/read']
Run Code Online (Sandbox Code Playgroud)

我看到这个问题似乎没有直接解决问题的答案:TensorFlow,如何重用变量范围名称

kma*_*o23 4

这是在上下文管理器中使用aswith来执行此操作的一种简单方法。somename使用此somename.original_name_scope属性,您可以检索该范围,然后向其中添加更多变量。下面是一个例子:

In [6]: with tf.variable_scope('myscope') as ms1:
   ...:   tf.Variable(1.0, name='var1')
   ...: 
   ...: with tf.variable_scope(ms1.original_name_scope) as ms2:
   ...:   tf.Variable(2.0, name='var2')
   ...: 
   ...: print([n.name for n in tf.get_default_graph().as_graph_def().node])
   ...: 
['myscope/var1/initial_value', 
 'myscope/var1', 
 'myscope/var1/Assign', 
 'myscope/var1/read', 
 'myscope/var2/initial_value', 
 'myscope/var2', 
 'myscope/var2/Assign', 
 'myscope/var2/read']
Run Code Online (Sandbox Code Playgroud)

备注
另请注意,设置reuse=True是可选的;也就是说,即使你通过了reuse=True,你仍然会得到相同的结果。


另一种方法(感谢OP本人!)是在重用/变量作用域的末尾添加它,如下例所示:

In [13]: with tf.variable_scope('myscope'):
    ...:   tf.Variable(1.0, name='var1')
    ...: 
    ...: # reuse variable scope by appending `/` to the target variable scope
    ...: with tf.variable_scope('myscope/', reuse=True):
    ...:   tf.Variable(2.0, name='var2')
    ...: 
    ...: print([n.name for n in tf.get_default_graph().as_graph_def().node])
    ...: 
['myscope/var1/initial_value', 
 'myscope/var1', 
 'myscope/var1/Assign', 
 'myscope/var1/read', 
 'myscope/var2/initial_value', 
 'myscope/var2', 
 'myscope/var2/Assign', 
 'myscope/var2/read']
Run Code Online (Sandbox Code Playgroud)

备注
请注意,设置reuse=True也是可选的;也就是说,即使你通过了reuse=True,你仍然会得到相同的结果。