我们知道tensorflow一旦构建了图,就不能在训练的时候改变了。而且输入一旦加入到图中,那么数据就会在一系列的参数流动,并且这一系列参数只能作用于从这个输入接口送进来的数据。如果此时我们又得到了一组数据,或者是一条队列,我们想让这条队列的数据走过和上一条输入队列一样的路线,换言之我们想实现这样的操作:
input_1 = tf.placeholder(...)
out_1 = model(input_1)
input_2 = tf.placeholder(...)
out_2 = model(input_2)
这样会出错。我们看以下代码:
import tensorflow as tf
import vgg
inputs_1 = tf.random_normal([10,224,224,3])
inputs_2 = tf.random_normal([10,224,224,3])
with tf.variable_scope('vgg_16') :
net ,end_points = vgg.vgg_16(inputs_1,100,False)
# tf.get_variable_scope().reuse_variables()
net_, end_points_ = vgg.vgg_16(inputs_2,100,False)
with tf.Session() as sess:
print("no error")
如果上述代码无误,最终可以输出 no error
但是错误信息是这样的:
ValueError: Variable vgg_16/vgg_16/conv1/conv1_1/weights already exists, disallowed.
Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope? Originally defined at:
意思就是某个变量已经存在了,不能这样再次生成这个变量。其实就是因为第一个输入进去生成了一系列的变量,这些变量只能用于第一个输入送来的数据。现在第二个输入也想用第一个输入对应的参数,这是不行的。那解决方法就是加上那一行注释:
import tensorflow as tf
import vgg
inputs_1 = tf.random_normal([10,224,224,3])
inputs_2 = tf.random_normal([10,224,224,3])
with tf.variable_scope('vgg_16') :
net ,end_points = vgg.vgg_16(inputs_1,100,False)
tf.get_variable_scope().reuse_variables()
net_, end_points_ = vgg.vgg_16(inputs_2,100,False)
with tf.Session() as sess:
print("no error")
tf.get_variable_scope().reuse_variables() 将在当前的variable_scope下,将变量设置为reuse = True,看名字也能知道代表的意义,就是两个输入可以共享变量了