创建方法
- tf.Variable()
weights = tf.Variable(tf.random_normal([784, 200]), name='weights')
- tf.get_variable()
weights = tf.get_variable(name='weights', shape=[784, 200], initializer=tf.random_normal_initializer())
推荐tf.get_variable()
推荐使用tf.get_variable()
。在需要共享变量的场合,可以使得代码重构更加方便
关于tf.get_variable()
tf.get_variable()
可以重新使用一个已经存在的同名变量或者重新创建一个新的变量。比如:
a = tf.get_variable(name='v', shape=[1])
在Python中这个变量保存为a,而在TensorFlow中这个变量保存为v。如果进一步定义变量b
>>> b = tf.get_variable(name='v', shape=[1])
ValueError: Variable v already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope? Originally defined at:
出现这个错误的原因在于,在使用TensorFlow中一个已经定义的变量时,需要申明reuse。为了重复使用tf.get_variable()定义的变量,必须在variable_scope中声明reuse
with tf.variable_scope('one'):
a = tf.get_variable('v', [2])
with tf.variable_scope('one', reuse=True):
c = tf.get_variable('v', [2])
网友评论