【发布时间】:2017-08-23 03:16:50
【问题描述】:
from __future__ import print_function
import tensorflow as tf
def _var_init(name, shape, initializer=tf.contrib.layers.xavier_initializer(),
trainable=True):
with tf.device('/cpu:0'):
var = tf.get_variable(
name=name,
shape=shape,
initializer=initializer,
trainable=trainable
)
return var
def main():
sess = tf.Session()
# 1th case, it works
with tf.variable_scope('test1', reuse=False) as test1:
with tf.variable_scope('test2', reuse=False) as test2:
w1 = _var_init('w1', [1, 2])
sess.run(tf.global_variables_initializer())
print(sess.run(w1), w1)
# 2th case, it works
with tf.variable_scope('test1', reuse=True):
with tf.variable_scope('test2', reuse=False):
w2 = _var_init('w1', [1, 2])
print(sess.run(w2), w2)
# 3th case, it works
with tf.variable_scope(test1, reuse=False):
with tf.variable_scope(test2, reuse=True):
w3 = _var_init('w1', [1, 2])
print(sess.run(w3), w3)
# 4th case, ValueError: Variable test1/test2/w1 already exists.
with tf.variable_scope(test1, reuse=True):
with tf.variable_scope(test2, reuse=False):
w4 = _var_init('w1', [1, 2])
print(sess.run(w4), w4)
# 5th case, ValueError: Variable test1/test2/w1 already exists.
with tf.variable_scope('test1', reuse=False):
with tf.variable_scope('test2', reuse=False):
w5 = _var_init('w1', [1, 2])
print(sess.run(w5), w5)
if __name__ == '__main__':
main()
第 1-3 种情况输出:
[[ 0.34345531 -0.84748644]] <tf.Variable 'test1/test2/w1:0' shape=(1, 2) dtype=float32_ref>
[[ 0.34345531 -0.84748644]] <tf.Variable 'test1/test2/w1:0' shape=(1, 2) dtype=float32_ref>
[[ 0.34345531 -0.84748644]] <tf.Variable 'test1/test2/w1:0' shape=(1, 2) dtype=float32_ref>
问题:
我很困惑为什么第 2 种情况有效,但第 4 种情况失败。 Tensorflow 不按 scope_name 搜索 variable_scope 吗?第2种情况和第4种情况有什么区别? (即with tf.variable_scope('test1', reuse=True):和with tf.variable_scope(test1, reuse=False):有什么区别?)
我认为他们以前是一样的。但现在它们看起来不同了。 tf.variable_scope 中的重用选项如何工作?
类似但不重复的问题:
【问题讨论】:
标签: python tensorflow with-statement