tf.get_variable_scope() 常用用法

我们知道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,看名字也能知道代表的意义,就是两个输入可以共享变量了

  • 8
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值