3.1 联系
两个函数都可以用于创建变量,
tf.Variable: initial_value必须指定, name可选
tf.Variable(
initial_value=None, trainable=None, validate_shape=True, caching_device=None,
name=None, variable_def=None, dtype=None, import_scope=None, constraint=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.compat.v1.VariableAggregation.NONE, shape=None
)
tf.get_variable: name, shape, initializer必须指定
tf.compat.v1.get_variable(
name, shape=None, dtype=None, initializer=None, regularizer=None,
trainable=None, collections=None, caching_device=None, partitioner=None,
validate_shape=True, use_resource=None, custom_getter=None, constraint=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.compat.v1.VariableAggregation.NONE
)
使用tf.Variable和tf.get_variable创建初始化为1, shape为[2,3]的变量。
a = tf.Variable(tf.constant(1, shape=[2, 3]))
b = tf.get_variable("b", shape=[2, 3], initializer=tf.constant_initializer(1))
3.2 区别
tf.get_variable可以通过变量名,进行创建或获取变量,name不可选。而tf.Variable只能进行创建变量,name可选。
如果需要通过tf.get_variable获取已经创建的变量,需要通过tf.variable_scope函数生成上下文管理器。
with tf.variable_scope("liang"):
v = tf.get_variable("sun", shape=(), initializer=tf.constant_initializer(1.0))
'''
with tf.variable_scope("liang"):
v = tf.get_variable("sun") # Error liang/sun:0 exists.
'''
with tf.variable_scope("liang", reuse=True):
v1 = tf.get_variable("sun")
print(v == v1) # True
'''
with tf.variable_scope("b", reuse=True):
v2 = tf.get_variable("s") # Error, b/s doesn't exist.
'''
注意
- 当创建变量时,不需要加reuse=True, 如果已经创建,则会报错。
- 当获取变量时,需要加reuse=True,如果没有创建,则会报错。
3.3 tf.variable_scope
tf.variable_scope可以创建命名空间,命名空间会加到变量名前。
### tf.variable_scope, create namespace.
vs = tf.get_variable("v", [1])
print(vs.name) # v:0
with tf.variable_scope("foo"):
vs2 = tf.get_variable("v", [1])
print(vs2.name) # foo/v:0
with tf.variable_scope("foo"):
with tf.variable_scope("bar"):
vs3 = tf.get_variable("v", [1])
print(vs3.name) # foo/bar/v:0
with tf.variable_scope("", reuse=True):
vs4 = tf.get_variable("foo/v")
print(vs4 == vs2) # True
vs5 = tf.get_variable("foo/bar/v")
print(vs5 == vs3) # True