充分理解 name / variable_scope

这篇文章写得非常好:https://blog.csdn.net/Jerr__y/article/details/70809528
总结几个点:
1、tf.Variable在命名冲突的时候会自动重命名,如命名为w,第二个机会变成w_1。tf.placeholder也会,tf.get_variable则不会。
2、tf.name_scope是不会对tf.get_variable有影响的,对tf.Variable有影响。只有tf.variable_scope对两者都有。
3、tf.variable_scope和tf.get_variable主要是为共享变量用的。原因如上面那篇文章3.1所示,在卷积或者lstm时,我们需要共享变量,如果只是用了tf.Variable,那么会创建新的变量,如果只用tf.get_variable又会冲突。
所以要reuse,方式主要有两种:
转自:https://blog.csdn.net/u012436149/article/details/52838757

with tf.variable_scope("try"):
    #先创建两个变量w1, w2
    w2 = tf.get_variable("w1",shape=[2,3,4], dtype=tf.float32)
    w3 = tf.get_variable("w2", shape=[2, 3, 4], dtype=tf.float32)
    #使用reuse_variables 将刚刚创建的两个变量共享
    tf.get_variable_scope().reuse_variables()
    w4 = tf.get_variable("w1", shape=[2, 3, 4], dtype=tf.float32)
    w5 = tf.get_variable("w2", shape=[2, 3, 4], dtype=tf.float32)
    #再进行共享的话,还需要再使用一次reuse_variables()
    tf.get_variable_scope().reuse_variables()
    w6 = tf.get_variable("w1", shape=[2, 3, 4], dtype=tf.float32)
    w7 = tf.get_variable("w2", shape=[2, 3, 4], dtype=tf.float32)

猜你喜欢

转载自blog.csdn.net/u013061183/article/details/80641692