我正在尝试使用具有多个塔的张量流来训练网络。我为所有塔楼设置了reuse = True
。但是在cifar10 multi gpu train of tensorflow tutorials中,重用变量在第一个塔创建后设置了:
with tf.variable_scope(tf.get_variable_scope()):
for i in xrange(FLAGS.num_gpus):
with tf.device('/gpu:%d' % i):
with tf.name_scope('%s_%d' % (cifar10.TOWER_NAME, i)) as scope:
# Dequeues one batch for the GPU
image_batch, label_batch = batch_queue.dequeue()
# Calculate the loss for one tower of the CIFAR model. This function
# constructs the entire CIFAR model but shares the variables across
# all towers.
# Actually the logits (whole network) is defined in tower_loss
loss = tower_loss(scope, image_batch, label_batch)
# Reuse variables for the next tower.
tf.get_variable_scope().reuse_variables()
它有什么不同吗?如果我们事先设置reuse = True会发生什么?
答案 0 :(得分:2)
第一次运行需要reuse=False
才能生成变量。如果reuse = True但是尚未构造变量,则会出错。
如果您使用较新版本的tensorflow(我认为> 1.4),您可以使用reuse=tf.AUTO_REUSE
,它将为您带来魔力。
我不确定这与您拥有的多设备设置有何关联。仔细检查变量名称是否不会被设备作为前缀。在这种情况下,没有重用,每个设备都有不同的变量。
答案 1 :(得分:1)
share variables有两种方法。
版本1:
with tf.variable_scope("model"):
output1 = my_image_filter(input1)
with tf.variable_scope("model", reuse=True):
output2 = my_image_filter(input2)
或版本2:
with tf.variable_scope("model") as scope:
output1 = my_image_filter(input1)
scope.reuse_variables()
output2 = my_image_filter(input2)
两种方法共享变量。第二种方法用于Cifar10 tutorial,因为它更清洁(这只是我的意见)。您可以尝试使用版本1重建它,代码可能不太可读。