我喜欢做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()
时,我得到一个错误,说没有可共享的变量 . 当我在tensorboard中可视化图形时,我在 group_1
子图中有几个 weigths_*
.
1 回答
以下代码执行您想要的操作:
需要了解的一些重要事项:
name_scope()
影响所有操作 except variables created with get_variable() .要在范围中放置变量,需要使用
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()
函数很有用 .