如何在 Tensorflow 中将变量重用设置回 False?

How to set variable reuse back to False in Tensorflow?

在Tensorflow中,我们可以通过tf.get_variable_scope().reuse_variables()将变量重用设置为True,有什么办法可以在不离开范围的情况下将其设置回False吗?

这是不可能的。在关于共享变量的教程中,他们明确指出:

Note that you cannot set the reuse flag to False. The reason behind this is to allow to compose functions that create models. Imagine you write a function my_image_filter(inputs) as before. Someone calling the function in a variable scope with reuse=True would expect all inner variables to be reused as well. Allowing to force reuse=False inside the function would break this contract and make it hard to share parameters in this way

你必须离开你的范围并打开另一个同名的 reuse=False

您可以做的是:

print tf.get_variable_scope().reuse
with tf.variable_scope(tf.get_variable_scope(), reuse=True): 
  print tf.get_variable_scope().reuse
  # Code that reuse variables goes here
print tf.get_variable_scope().reuse

输出:

 False
 True
 False

因此只需将需要重用变量的代码部分放在 with 中即可。