DAY 4
1
Google Developers Machine Learning

## 【04】tensorflow 到底該用 name scope 還是 variable scope

``````with tf.name_scope('name'):
tf.placeholder(tf.int32, name='i1')

with tf.variable_scope('variable'):
tf.placeholder(tf.int32, name='i2')
``````

tensorboard 觀察結果：

``````tf.get_variable
tf.Variable
``````

``````tf.Variable(name="V", initial_value=0)
tf.Variable(name="V", initial_value=0)
``````

``````tf.get_variable(name="V", shape=[1])
tf.get_variable(name="V", shape=[1])  # it will crash
``````

``````tf.get_variable(name="V", shape=[1])
tf.Variable(name="V", initial_value=0)
tf.Variable(name="V", initial_value=0)
``````

tensorboard 觀察結果：

``````tf.Variable(name="V", initial_value=0)
tf.get_variable(name="V", shape=[1])
tf.Variable(name="V", initial_value=0)
``````

get_variable()只在 variable scope 底下有反應，按照 tensorflow 的規則，如果你使用了get_variable()，又想將它放置在某個 scope 底下，那麼請使用 variable_scope。

``````with tf.name_scope('name'):
tf.get_variable(name="V", shape=[1])

with tf.variable_scope('variable'):
tf.get_variable(name="V", shape=[1])
``````

tensorboard 觀察結果：

``````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
``````

``````with tf.variable_scope("foo") as scope:
v = tf.get_variable("v", [1])

# 其他程式
# ...
# ...
# ...
# ...

scope.reuse_variables()
v1 = tf.get_variable("v", [1])

assert v1 == v
``````

tensorflow 官方說明文件還有許多例子，這邊我只挑幾個出來，希望對大家有幫助，理解以上幾個觀念，可避免實作上採很多雷了。

Github原始碼

https://www.tensorflow.org/api_docs/python/tf/name_scope