为什么我们在 Tensorflow 中命名变量?

Why do we name variables in Tensorflow?

在某些地方,我看到了语法,其中变量用名称初始化,有时没有名称。例如:

# With name
var = tf.Variable(0, name="counter")

# Without
one = tf.constant(1)

命名变量有什么意义 var "counter"?

name参数是可选的(你可以创建有或没有它的变量和常量),你在程序中使用的变量不依赖于它。名称可以在几个地方提供帮助:

当您想保存或恢复变量时(您可以save them to a binary file after the computation). From docs:

By default, it uses the value of the Variable.name property for each variable

matrix_1 = tf.Variable([[1, 2], [2, 3]], name="v1")
matrix_2 = tf.Variable([[3, 4], [5, 6]], name="v2")
init = tf.initialize_all_variables()

saver = tf.train.Saver()

sess = tf.Session()
sess.run(init)
save_path = saver.save(sess, "/model.ckpt")
sess.close()

尽管如此,您有变量 matrix_1matrix_2,它们在文件中保存为 v1v2

TensorBoard 中也使用名称来很好地显示边的名称。你甚至可以 group them by using the same scope:

import tensorflow as tf

with tf.name_scope('hidden') as scope:
  a = tf.constant(5, name='alpha')
  W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0), name='weights')
  b = tf.Variable(tf.zeros([1]), name='biases')

你可以把Python名字space和TensorFlow名字space想象成两个平行的宇宙。 TensorFlow space 中的名称实际上是属于任何 TensorFlow 变量的 "real" 属性,而 Python space 中的名称只是在此期间指向 TensorFlow 变量的临时指针 运行 你的脚本。这就是为什么在保存和恢复变量时,只使用 TensorFlow 名称的原因,因为脚本终止后 Python 名称space 不再存在,但 Tensorflow 名称space 仍然存在您保存的文件。

考虑以下用例代码及其输出

def f():
    a = tf.Variable(np.random.normal(), dtype = tf.float32, name = 'test123')

def run123():
    f()
    init = tf.global_variables_initializer()
    with tf.Session() as sess123:
        sess123.run(init)
        print(sess123.run(fetches = ['test123:0']))
        print(sess123.run(fetches = [a]))

run123()

输出:

[0.10108799]

NameError Traceback (most recent call last) in () 10 print(sess123.run(fetches = [a])) 11 ---> 12 run123()

in run123() 8 sess123.run(init) 9 print(sess123.run(fetches = ['test123:0'])) ---> 10 print(sess123.run(fetches = [a])) 11 12 run123()

NameError: name 'a' is not defined

'a',在 f() 的范围内定义,在其范围之外不可用,即在 run123() 中。但是默认图必须用一些东西来引用它们,以便可以根据需要在各种范围内引用默认图,这就是它的 name 派上用场的时候。

其实从区分不同变量的角度来说,我们完全可以使用python这个名字(赋值符号左边的部分,我们称这个名字为python name以免混淆.比如下面例子中的v)来命名变量。但是,在编程过程中,我们通常会将python名称重新绑定到其他对象(即Tensorflow中的op),例如

v = tf.get_variable("v1", [3], initializer = tf.zeros_initializer)
v = tf.get_variable("v2", [5], initializer = tf.zeros_initializer)

首先,python 名称 v 绑定张量形式的第一行 (tf.get_variable("v1", [3], initializer = tf.zeros_initializer))。然后,v 重新绑定第二行 (tf.get_variable("v2", [5], initializer = tf.zeros_initializer)) 的张量,不再绑定第一个张量。如果我们不给tensorflow属性名v1v2,我们如何从第一行识别张量呢?