一、变量作用域
import tensorflow as tf import os # 屏蔽info os.environ["TF_CPP_MIN_LOG_LEVEL"] = '2' # 方式一:我们之前的方式;变量数量会比较多的情况 def my_fun(x): w1 = tf.Variable(initial_value=tf.random_normal(shape=[2]))[0] b1 = tf.Variable(tf.random_normal(shape=[1]))[0] r1 = w1 * x + b1 w2 = tf.Variable(initial_value=tf.random_normal(shape=[2]))[0] b2 = tf.Variable(tf.random_normal(shape=[1]))[0] r2 = w2 * r1 + b2 return w1, b1, r1, w2, b2, r2 x = tf.constant(3, name='x', dtype=tf.float32) result = my_fun(x) # 构建变量初始化 init_op = tf.global_variables_initializer() # 执行阶段: with tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)) as sess: sess.run(init_op) print(sess.run(result))
# 方式二:通过变量作用域,共享变量 def my_fun2(x): # 参数initializer:初始化器 w = tf.get_variable(name='w', shape=[2], 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 w, b, r def func(x): r1 = my_fun2(x) r2 = my_fun2(r1[2]) return r1, r2 result = func(x) # 构建变量初始化 init_op = tf.global_variables_initializer() # 执行阶段: with tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)) as sess: sess.run(init_op) print(sess.run(result))
执行方式二,抛出异常:变量w, b, r已经定义,不允许重复定义
怎么解决?为变量w, b, r指定变量作用域,在func()函数中指定即可:
def func(x): with tf.variable_scope(name_or_scope='op1'): r1 = my_fun2(x) with tf.variable_scope(name_or_scope='op2'): r2 = my_fun2(r1[2]) return r1, r2
假如,现在有两个x,需要执行两次func(),得到两个result,将以下代码加入到构建阶段的代码中:
x2 = tf.constant(5, name='x', dtype=tf.float32) result2 = func(x)
执行新的代码,再次抛出异常:变量op1/w已经存在,不允许重复定义。
怎么解决?再多添加一层作用域,改变op1/w的变量作用域?不需要这样,
tf.variable_scope()的参数reuse=tf.AUTO_REUSE,使得变量作用域变长,不会出现重复定义的情况
import tensorflow as tf import os # 屏蔽info os.environ["TF_CPP_MIN_LOG_LEVEL"] = '2' # 方式二:通过变量作用域,共享变量 def my_fun2(x): # 参数initializer:初始化器 w = tf.get_variable(name='w', shape=[2], 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 w, b, r def func(x): with tf.variable_scope(name_or_scope='op1', reuse=tf.AUTO_REUSE): r1 = my_fun2(x) with tf.variable_scope(name_or_scope='op2', reuse=tf.AUTO_REUSE): r2 = my_fun2(r1[2]) return r1, r2 x = tf.constant(3, name='x', dtype=tf.float32) result = func(x) x2 = tf.constant(5, name='x', dtype=tf.float32) result2 = func(x) # 构建变量初始化 init_op = tf.global_variables_initializer() # 执行阶段: with tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)) as sess: sess.run(init_op) print(sess.run(result)) print(sess.run(result2))
总结:
二、 15、TensorFlow的作用域name_scope