为什么我们在 Tensorflow 中命名变量? [英] Why do we name variables in Tensorflow?

查看:24
本文介绍了为什么我们在 Tensorflow 中命名变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In some of the places, I saw the syntax, where variables are initialized with names, sometimes without names. For example:

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

# Without
one = tf.constant(1)

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

What is the point of naming the variable var "counter"?

推荐答案

name 参数是可选的(你可以使用或不使用它来创建变量和常量),以及你在程序中使用的变量不依赖于它.名称在以下几个方面很有用:

The name parameter is optional (you can create variables and constants with or without it), and the variable you use in your program does not depend on it. Names can be helpful in a couple of places:

当您想要保存或恢复变量时(您可以将它们保存到计算后的二进制文件).来自文档:

默认情况下,它使用 Variable.name 属性的值对每个变量

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.

Nonetheless you have variables matrix_1, matrix_2 they are saves as v1, v2 in the file.

TensorBoard 中也使用了名称来很好地显示边的名称.您甚至可以使用相同的范围将它们分组:

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')

这篇关于为什么我们在 Tensorflow 中命名变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆