What is the difference between variable_scope
and name_scope
? The variable scope tutorial talks about variable_scope
implicitly opening name_scope
. I also noticed that creating a variable in a name_scope
automatically expands its name with the scope name as well. So what is the difference?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- batch_dot with variable batch size in Keras
- How to get the background from multiple images by
- Evil ctypes hack in python
tf.variable_scope
is an evolution oftf.name_scope
to handleVariable
reuse. As you noticed, it does more thantf.name_scope
, so there is no real reason to usetf.name_scope
: not surprisingly, a TF developper advises to just usetf.variable_scope
.My understanding for having
tf.name_scope
still lying around is that there are subtle incompatibilities in the behavior of those two, which invalidatestf.variable_scope
as a drop-in replacement fortf.name_scope
.I had problems understanding the difference between variable_scope and name_scope (they looked almost the same) before I tried to visualize everything by creating a simple example:
Here I create a function that creates some variables and constants and groups them in scopes (depending by the type I provided). In this function I also print the names of all the variables. After that I executes the graph to get values of the resulting values and save event-files to investigate them in tensorboard. If you run this, you will get the following:
You see the similar pattern if you open TB (as you see
b
is outside ofscope_name
rectangular):This gives you the answer:
Now you see that
tf.variable_scope()
adds a prefix to the names of all variables (no matter how you create them), ops, constants. On the other handtf.name_scope()
ignores variables created withtf.get_variable()
because it assumes that you know which variable and in which scope you wanted to use.A good documentation on Sharing variables tells you that
The same documentation provides a more details how does Variable Scope work and when it is useful.
When you create a variable with
tf.get_variable
instead oftf.Variable
, Tensorflow will start checking the names of the vars created with the same method to see if they collide. If they do, an exception will be raised. If you created a var withtf.get_variable
and you try to change the prefix of your variable names by using thetf.name_scope
context manager, this won't prevent the Tensorflow of raising an exception. Onlytf.variable_scope
context manager will effectively change the name of your var in this case. Or if you want to reuse the variable you should call scope.reuse_variables() before creating the var the second time.In summary,
tf.name_scope
just add a prefix to all tensor created in that scope (except the vars created withtf.get_variable
), andtf.variable_scope
add a prefix to the variables created withtf.get_variable
.