情况一:w = tf.get_variable
在with tf.variable_scope(name=‘op’):下有使用w的相关代码,这样,会话中第一次执行到with tf.variable_scope(name=‘op’):的w相关代码时,用的w是第一次用初始化器构造的值,下一次用,发现w已经有值了,直接拿来用。
情况二w = tf.get_variable
既在with tf.variable_scope(‘op1’):下,又在with tf.variable_scope(‘op2’):下,都有使用w的代码,这样,会话中第一次执行with tf.variable_scope(‘op1’):下的w相关代码时,用到的w是第一次用初始化器构造的值w
1,紧接着又执行with tf.variable_scope(‘op2’):下的w相关的代码,会再次用初始化器构造值w2,然后去使用。 那后面,执行with tf.variable_scope(‘op1’):下的w的相关代码时,用的w现在已经有值了,就是w1;;;;执行with tf.variable_scope(‘op2’):下的w的相关代码时,用的w现在也已经有值了,就是w2。 这样,w就实现了共享。
def my_func(x):
# initializer:初始化器 第一次运行没问题,第二次运行时那个值已经存在了,但默认情况下它是不能存在的
w = tf.get_variable(name='w', shape=[1], initializer=tf.random_normal_initializer())[0]
# tf.random_normal_initializer()同tf.random_normal()类似
b = tf.get_variable(name='b', shape=[1], initializer=tf.random_normal_initializer())[0]
# 有对应名称(比如:name='w')的变量就获取,没有就创建
r = w * x + b
return r, w, b
def func(x):
with tf.variable_scope("op1", reuse=tf.AUTO_REUSE):
r1 = my_func(x)
with tf.variable_scope("op2", reuse=tf.AUTO_REUSE):
r2 = my_func(r1[0])
return r1, r2
# 下面两行代码还是属于图的构建
x1 = tf.constant(3, dtype=tf.float32)
x2 = tf.constant(4, dtype=tf.float32)
r1 = func(x1)
r2 = func(x2)
with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)) as sess:
tf.global_variables_initializer().run()
print(sess.run([r1, r2]))
# 运行结果如下:
# [((5.179422, 1.2175516, 1.5267673), (1.7860048, 0.3359851, 0.045796324)),
# ((6.3969736, 1.2175516, 1.5267673), (2.195084, 0.3359851, 0.045796324))]
小理解
a = tf.Variable(1.0, name='a', dtype=tf.float32)
b = tf.get_variable(name='b', shape=[1], initializer=tf.random_normal_initializer())[0]
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(a, feed_dict={a: 2.0})) # 2.0
print(sess.run(b)) # -1.0582993
print(sess.run(b, feed_dict={b: 2.0})) # 2.0