tf.Variable()
W = tf.Variable(<initial-value>, name=<optional-name>)
无法共享变量,必须指定初始化值;每次都会新建一个变量
tf.get_variable()
W = tf.get_variable(name, shape=None, dtype=tf.float32, initializer=None, regularizer=None, trainable=True, collections=None)
获取已存在的变量(要求不仅名字,而且初始化方法等各个参数都一样),如果不存在,就新建一个。
可以用各种初始化方法,不用明确指定值
with tf.variable_scope("one"): # reuse默认为False
a = tf.get_variable("v", [1]) # a.name == "one/v:0"
with tf.variable_scope("one"):
b = tf.get_variable("v", [1]) # 创建名字一样的变量会报错 ValueError: Variable one/v already exists
with tf.variable_scope("one", reuse = True): # 设置reuse=True,默认为False。
c = tf.get_variable("v", [1]) #c.name == "one/v:0" 成功共享,因为设置了reuse
变量共享的前提是,在同一 variable_scope reuse=False 默认 reuse=True 共享同名变量,存在时指向同一内存空间,不存在报错 reuse=tf.AUTO_REUSE 存在时指向同一内存空间,不存在时创建此变量
故,用 tf.AUTO_REUSE 更好,防止要共享的变量不存在时报错