tf.variable 与张​​量流中的 tf.constant

tf.variable vs tf.constant in tensorflow

我运行以下代码改为

 W = tf.Variable(tf.zeros([1, 3]), dtype=tf.float32, name="W")
 B = tf.constant([[1, 2, 3]], dtype=tf.float32, name="B")
 act = tf.add(W, B)
 init = tf.global_variables_initializer()
 with tf.Session() as sess:
     sess.run(init)
     sess.run(act)
     writer = tf.summary.FileWriter("./graphs", sess.graph)
 writer.close()

并用tensorboard验证:

让我感到困惑的是 read 操作和表示为 (W) 之前的操作。常量 B 直接指向 Add 操作,而 tf.variable 包含所有这些操作节点。这是我的问题:

  1. 什么是(W)操作?常量 B 是一个规则的圆圈,表示一个常量。椭圆形节点表示操作节点。 (W) 看起来不像任何操作,但它用相同的椭圆形节点表示?该节点的工作是什么?

  2. Add 节点使用 read 操作显式读取 (W) 节点,而不是常量节点 B。为什么变量节点需要read

W操作是tf.Variable你在这里声明:W = tf.Variable(tf.zeros([1, 3]), dtype=tf.float32, name="W")。在幕后它做了很多操作(比如 W.initializer - 你的初始化操作, W.value() 你的读操作,W.assign() 给自己赋值,可能更多)。您还会看到您的初始值 zeros

所有这些都是 tf.Variable 内部的,您不必担心。这就是为什么所有这些都在大红色边框后面从您那里折叠(抽象掉)的原因。

由于缺少任何中级文档的 link,这是我实用的、概念性的 模型 的 tensorflow 变量。

以下,来自 https://www.tensorflow.org/programmers_guide/graphs#visualizing_your_graph 似乎至少暗示了你问题的答案。

"Executing v = tf.Variable(0) adds to the graph a tf.Operation that will store a writeable tensor value that persists between tf.Session.run calls. The tf.Variable object wraps this operation, and can be used like a tensor, which will read the current value of the stored value. The tf.Variable object also has methods such as assign and assign_add that create tf.Operation objects that, when executed, update the stored value."

这来自 https://www.tensorflow.org/programmers_guide/variables

"Internally, a tf.Variable stores a persistent tensor. Specific ops allow you to read and modify the values of this tensor. "

这来自 http://www.goldsborough.me/tensorflow/ml/ai/python/2017/06/28/20-21-45-a_sweeping_tour_of_tensorflow/

"variables are in-memory buffers containing tensors."

请注意,图的节点之间的线必须是张量。 tf.constant(...) returns 一个(class 的实例)张量。但是,tf.Variable(...) returns 不是 Tensor 实例,而是 class Variable

的实例
x = tf.Variable(...)
print(type(x)) #  <class 'tensorflow.python.ops.variables.Variable'>
y = tf.constant(...)
print(type(y)) # <class 'tensorflow.python.framework.ops.Tensor'>

要在操作中使用 tf 变量(其参数必须是张量),其值必须首先 "transformed" 转换为张量,并且 "read" 操作 returns "hidden" 变量代表的张量。我相信该值以 tf.constant(张量)的形式返回。

注意tf.Variable(...)中的大写V,tf.constant(..)中的小写c 。一个 tf.Variable(...) returns 一个 tf.Variable class 的实例,所以 tf.Variable(...) 实例化一个 class 实例,并且 read() 是此 class 上的一个(a 的可视化)方法,其中 returns 一个值。当一个值被分配给一个变量时,它会修改这个 "hidden" 张量。

另一方面,至少在概念上,tf.constant(...) 是一个工厂函数,returns 是 class 张量的一个实例。

如果有一些关于此的中级文档 link 就好了。