Tensorflow 1.x如何遍历给定张量的计算图?
这个问题与低级Tensorflow 1.x API有关。给定一个Tensorflow 1.x如何遍历给定张量的计算图?,tensorflow,Tensorflow,这个问题与低级Tensorflow 1.x API有关。给定一个Tensor到Session.run(),我不清楚Tensorflow如何遍历计算图 假设我有如下代码: a = tf.constant(1.0) b = tf.subtract(a, 1.0) c = tf.add(b, 2.0) d = tf.multiply(c,3) sess = tf.Session() sess.run(d) 减法、加法和乘法运算不都存储在张量d中,对吗?我知道Tensor对象有graph和op字段;
Tensor
到Session.run()
,我不清楚Tensorflow如何遍历计算图
假设我有如下代码:
a = tf.constant(1.0)
b = tf.subtract(a, 1.0)
c = tf.add(b, 2.0)
d = tf.multiply(c,3)
sess = tf.Session()
sess.run(d)
减法、加法和乘法运算不都存储在张量d
中,对吗?我知道Tensor
对象有graph
和op
字段;这些字段是如何递归访问以获得计算d
所需的所有操作的
编辑:添加输出
print(tf.get_default_graph().as_graph_def())
node {
name: "Const"
op: "Const"
attr {
key: "dtype"
value {
type: DT_FLOAT
}
}
attr {
key: "value"
value {
tensor {
dtype: DT_FLOAT
tensor_shape {
}
float_val: 1.0
}
}
}
}
node {
name: "Sub/y"
op: "Const"
attr {
key: "dtype"
value {
type: DT_FLOAT
}
}
attr {
key: "value"
value {
tensor {
dtype: DT_FLOAT
tensor_shape {
}
float_val: 1.0
}
}
}
}
node {
name: "Sub"
op: "Sub"
input: "Const"
input: "Sub/y"
attr {
key: "T"
value {
type: DT_FLOAT
}
}
}
node {
name: "Add/y"
op: "Const"
attr {
key: "dtype"
value {
type: DT_FLOAT
}
}
attr {
key: "value"
value {
tensor {
dtype: DT_FLOAT
tensor_shape {
}
float_val: 2.0
}
}
}
}
node {
name: "Add"
op: "Add"
input: "Sub"
input: "Add/y"
attr {
key: "T"
value {
type: DT_FLOAT
}
}
}
node {
name: "Mul/y"
op: "Const"
attr {
key: "dtype"
value {
type: DT_FLOAT
}
}
attr {
key: "value"
value {
tensor {
dtype: DT_FLOAT
tensor_shape {
}
float_val: 3.0
}
}
}
}
node {
name: "Mul"
op: "Mul"
input: "Add"
input: "Mul/y"
attr {
key: "T"
value {
type: DT_FLOAT
}
}
}
versions {
producer: 38
}
这就是Tensorflow静态计算图的全部要点。构建图形时,Tensorflow会在后台隐式构建一个静态图形。然后,当您在图中执行一个节点时,Tensorflow知道导致该节点的确切操作集。这有几个好处:
print(tf.get_default_graph().as_graph_def())
例如,如果在小型图形上执行此操作,您将看到以下内容,从节点d=tf.multiply(c,3)
开始:
然后c=tf.add(b,2.0)
:
然后b=tf.减去(a,1.0)
:
最后,a=tf.常数(1.0)
:
谢谢gorjan,这很有道理。因此,从
d
,TF可以找到op(d.op
),在这种情况下,它是乘法的,然后TF可以找到op的输入(张量),然后找到它们的ops,依此类推,基本上是从d
进行DFS。刚刚看到您的编辑。我运行命令并将输出粘贴到问题。出于某种原因,所有常量操作数的名称都是用/y
命名的。TBH,我不是Tensorflow的开发人员,只是指出我读过的东西和我的直觉。当谈到如何计算后台的操作时,我不想分享我不确定的信息。当然,没问题!在TF的图中,节点是运算,边是张量。我想也可能是另一种情况(张量是节点,运算是边)。但这完全是另一种讨论:)节点就是操作。每个运算的输出是一个张量。两个节点之间的边是将从一个节点流向另一个节点的张量类型/形状等的参考。
name: "Mul"
op: "Mul"
input: "Add"
name: "Add"
op: "Add"
input: "Sub"
name: "Sub"
op: "Sub"
input: "Const"
name: "Const"
op: "Const"