Tensorflow中使用tf.variable_scope()而scope名字自动加"_1"

最近在使用tf.variable_scope()对参数进行空间的划分,结果在最后保存为pb文件时,发现scope名字中莫名地被自动添加了"_1"、"_2"等内容,如下代码所示

with tf.variable_scope('test'):
    p1 = tf.placeholder(tf.float32, shape=(3,3), name='p1')    #output: test/p1
    v1 = tf.get_variable('v1', shape=(3,3), name='v1')    #output: test/v1

with tf.variable_scope('test'):
    p2 = tf.placeholder(tf.float32, shape=(3,3), name='p2') #output: test_1/p2
    v2 = tf.get_variable('v2', shape=(3,3), name='v2')    #output: test/v2

经查证,这是tf开发人员有意而为之,不是bug!

在经过一番折腾之后,发现tf.name_scope()也会有这种类似的意外:

with tf.name_scope('test'):
    p1 = tf.placeholder(tf.float32, shape=(3,3), name='p1')    #output: test/p1

with tf.name_scope('test'):
    p2 = tf.placeholder(tf.float32, shape=(3,3), name='p2')    #output: test_1/p2

综合上面tf.variable_scope()和tf.name_scope()的结果,貌似对ops而言二者效果一样。在查阅tf源码的VariableScope类之后发现,该类有一个属性为original_name_scope,返回的值是传递给name_scope的值,猜测tf.variable_scope()在作用于ops时会调用tf.name_scope()。

基于这个推测,上面两端代码的结果也就能够理解了。那么为什么name_scope的名字不能重复呢?我的理解是:对于ops来说不涉及需不需要reuse的问题,所以系统自动加上"_1"的后缀。而对于variable来说,有可能会需要同一空间中该变量的值,所以名字需要一致。

猜你喜欢

转载自blog.csdn.net/u010970514/article/details/82121047
今日推荐