我想在两个子图之间共享变量。更准确地说,我想要做一个fowolling操作:给定4个张量a、b、c、d和一个权重变量w,计算W*a、W*b、W*c、W*d,但是在不同的子图中。我的代码如下:
def forward(inputs):
w = tf.get_variable("weights", ...)
return tf.matmult(w, inputs)
with tf.name_scope("group_1"):
a = tf.placeholder(...)
b = tf.placeholder(...)
c = tf.placeholder(...)
aa = forward(a)
bb = forward(b)
cc = forward(c)
with tf.name_scope("group_2):
d = tf.placeholder(...)
tf.get_variable_scope().reuse_variable()
dd = forward(d)这个例子似乎正在运行,但我不确定变量W是否被重用,特别是在group_1中,当我添加tf.get_variable_scope.reuse_variable()时,我看到一个错误,说明没有变量可以共享。当我在张图中可视化图形时,我确实在group_1子图中有几个group_1。
发布于 2016-09-10 14:12:26
下面的代码可以实现您想要的结果:
import tensorflow as tf
def forward(inputs):
init = tf.random_normal_initializer()
w = tf.get_variable("weights", shape=(3,2), initializer=init)
return tf.matmul(w, inputs)
with tf.name_scope("group_1"):
a = tf.placeholder(tf.float32, shape=(2, 3), name="a")
b = tf.placeholder(tf.float32, shape=(2, 3), name="b")
c = tf.placeholder(tf.float32, shape=(2, 3), name="c")
with tf.variable_scope("foo", reuse=False):
aa = forward(a)
with tf.variable_scope("foo", reuse=True):
bb = forward(b)
cc = forward(c)
with tf.name_scope("group_2"):
d = tf.placeholder(tf.float32, shape=(2, 3), name="d")
with tf.variable_scope("foo", reuse=True):
dd = forward(d)
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
print(bb.eval(feed_dict={b: np.array([[1,2,3],[4,5,6]])}))
for var in tf.all_variables():
print(var.name)
print(var.eval())有几件重要的事情需要理解:
get_variable().创建的变量外,name_scope()还会影响所有操作系统。variable_scope()。例如,占位符a、b和c实际上名为"group_1/a"、"group_1/b"、"group_1/c"和"group_1/d",但weights变量名为"foo/weights"。因此,名称范围中的get_variable("weights")、"group_1"和变量作用域"foo"实际上都在查找"foo/weights"。如果您不确定存在哪些变量以及这些变量是如何命名的,则all_variables()函数非常有用。
https://stackoverflow.com/questions/36237427
复制相似问题