我可以发现两者之间的两个主要区别:首先,tf.Variable将始终创建一个新变量,而tf.get_variable从图中获取一个具有指定参数的现有的变量,如果它不存在,则创建一个新变量。
tf.Variable要求指定初始值。
必须澄清的是,函数tf.get_variable在名称前面加上当前变量作用域以执行重用检查。例如:with tf.variable_scope("one"):
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):
c = tf.get_variable("v", [1]) #c.name == "one/v:0"
with tf.variable_scope("two"):
d = tf.get_variable("v", [1]) #d.name == "two/v:0"
e = tf.Variable(1, name = "v", expected_shape = [1]) #e.name == "two/v_1:0"
assert(a is c) #Assertion is true, they refer to the same object.
assert(a is d) #AssertionError: they are different objects
assert(d is e) #AssertionError: they are different objects
最后一个断言错误很有意思:在同一范围内同名的两个变量应该是同一个变量。但是如果你测试变量名d和e,你会发现Tensorflow改变了变量名e:d.name #d.name == "two/v:0"
e.name #e.name == "two/v_1:0"