tensorflow 新建变量

2019-08-07  本文已影响0人  snowpigppp

创建方法

weights = tf.Variable(tf.random_normal([784, 200]), name='weights')
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])
上一篇 下一篇

猜你喜欢

热点阅读