且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在默认情况下不创建新作用域的情况下重用tensorflow中的变量作用域?

更新时间:2022-04-11 01:07:35

这是在上下文管理器中使用assomename的一种简单方法.使用此somename.original_name_scope属性,您可以检索该范围,然后向其添加更多变量.下面是一个说明:

Here is one straightforward way to do this using as with somename in a context manager. Using this somename.original_name_scope property, you can retrieve that scope and then add more variables to it. Below is an illustration:

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']

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

Remark
Please also note that setting reuse=True is optional; That is, even if you pass reuse=True, you'd still get the same result.

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

Another way (thanks to OP himself!) is to just add / at the end of the variable scope when reusing it as in the following example:

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']

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

Remark:
Please note that setting reuse=True is again optional; That is, even if you pass reuse=True, you'd still get the same result.