1.tf.Variable
2.tf.get_variable和tf.variable_scope
import tensorflow as tf
def my_func(x):
w1 = tf.Variable(tf.random_normal([1]))[0]
b1 = tf.Variable(tf.random_normal([1]))[0]
r1 = w1*x+b1
w2 = tf.Variable(tf.random_normal([1]))[0]
b2 = tf.Variable(tf.random_normal([1]))[0]
r2 = w2*r1+b2
return r1, w1, b1, r2, w2, b2
x = tf.constant(3, dtype=tf.float32)
r = my_func(x)
with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)) as sess:
tf.global_variables_initializer().run()
print(sess.run(r))
'''
'''
def my_func(x):
w = tf.Variable(tf.random_normal([1]))[0]
b = tf.Variable(tf.random_normal([1]))[0]
r = w * x + b
return r, w, b
def func(x):
r1 = my_func(x)
r2 = my_func(r1[0])
return r1, r2
x = tf.constant(3, dtype=tf.float32)
r = func(x)
with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)) as sess:
tf.global_variables_initializer().run()
print(sess.run(r))
'''
'''
def my_func(x):
w = tf.get_variable(name='w', shape=[1], initializer=tf.random_normal_initializer())[0]
b = tf.get_variable(name='b', shape=[1], initializer=tf.random_normal_initializer())[0]
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))]
''
'''