最近在学习使用TensorFlow,一直没有搞明白其中的get_variable()与Variable()的区别,今天特意在网上搜了一些资料,这里将一篇写的简单易懂的一篇外国博客分享给大家:http://www.machinelearningtutorial.net/fullpage/an-introduction-to-tensorflow-variables/ 。为了巩固自己的理解,自己先翻译一波。
TensorFlow中变量的定义
TensorFlow使用变量存储张量,通过一定的操作可以允许你读取或者修改张量。
变量的可以使用以下的方法创建:
import tensorflow as tf
var = tf.Variable(tf.truncated_normal([3]))
TensorFlow中的变量是惰性加载的,如果你想看到变量的值,必须建立一个对话(Session)
import tensorflow as tf
var = tf.Variable(tf.truncated_normal([3]))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(var))
创建和初始化
TensorFlow一般有两种方法创建变量:
通过tf.Variable()
weights = tf.Variable(tf.random_normal([784, 200]), name='weights')
通过tf.get_variable()
import tensorflow as tf
weights = tf.get_variable(name='weights', shape=[784, 200], initializer=tf.random_normal_initializer())
选择tf.Variable还是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])