tf.variable_scope变量管理

1、新建变量

with tf.variable_scope("foo"):
    v = tf.get_variable("v", [1])

reuse默认False,不可在同一命名空间建同一个变量,否则报错
2、获取同一命名空间的变量,利用reuse

with tf.variable_scope("foo"):
    v = tf.get_variable("v", [1])
with tf.variable_scope("foo",reuse=True):
    v1 = tf.get_variable("v", [1])
vv=[12]
with tf.Session()as sess:
    init=tf.global_variables_initializer()
    sess.run(init)
    fect={v:vv}
    v,v1=sess.run([v,v1],feed_dict=fect)

输出

[12.]  [12.] 

reuse=True,变量空间不变,只是把变量拿来用
3、获取同一命名空间的变量,利用scope.reuse_variables

with tf.variable_scope("foo"):
    v = tf.get_variable("v", [1])
with tf.variable_scope("foo") as scope:
    scope.reuse_variables()
    v1 = tf.get_variable("v", [1])
    f1=v1+v
vv=[12]
with tf.Session()as sess:
    init=tf.global_variables_initializer()
    sess.run(init)
    fect={v:vv}
    v,v1,f1=sess.run([v,v1,f1],feed_dict=fect)
    print(v,v1,f1)

输出

[12.] [12.] [24.]

变量空间不变,只是把变量拿来用
4、空间1利用空间2中变量

with tf.variable_scope("foo"):
    v = tf.get_variable("v", [1])
    # scope.reuse_variables()
with tf.variable_scope("f"):
    v1 = tf.get_variable("v", [1])
    f1=v1+v
vv=[12]
vv1=[22]
with tf.Session()as sess:
    init=tf.global_variables_initializer()
    sess.run(init)
    fect={v:vv,v1:vv1}
    v,v1,f1=sess.run([v,v1,f1],feed_dict=fect)
    # print(v,f1)
    print(v,v1,f1)

输出

[12.] [22.] [34.]

两个不同空间,可以直接用

猜你喜欢

转载自blog.csdn.net/angel_hben/article/details/84393858
今日推荐