首页 > 解决方案 > 节点和操作之间的区别

问题描述

我不明白 Tensorflow 中的节点和操作之间有什么区别。

例如:

with open('myfile_1','w') as myfile:
     for n in tf.get_default_graph().as_graph_def().node:
         myfile.write(n.name+'\n')



with open('myfile_2','w') as myfile:
     for op in tf.get_default_graph().get_operations():
         myfile.write(op.name+'\n')

什么进入 myfile_1 和什么进入 myfile_2 ?和变量属于哪个类/文件?

我们可以将它们都称为“张量”吗?我对这里的命名法有点困惑......

我在这里添加,按照评论中的建议,一个简单的图表上的结果:

tf.reset_default_graph()
x=tf.placeholder(tf.float32,[1])
y=2*x
z=tf.constant(3.0,dtype=tf.float32)
w=tf.get_variable('w',[2,3], initializer = tf.zeros_initializer())

with open('myfile_1','w') as myfile:
     for n in tf.get_default_graph().as_graph_def().node:
         myfile.write(n.name+'\n')

with open('myfile_2','w') as myfile:
     for op in tf.get_default_graph().get_operations():
         myfile.write(op.name+'\n')

with tf.Session() as sess:
     print(sess.run(y,feed_dict={x : [3]}))

在这种情况下 myfile_1 和 myfile_2 都等于:

Placeholder
mul/x
mul
Const
w/Initializer/zeros
w
w/Assign
w/read

标签: tensorflow

解决方案


Tensorflow 图是一个有向图,使得:

  • 节点 - 操作 (ops)。
  • 有向边 - 张量。

例如,当您定义:

x = tf.placeholder(tf.float32, shape=(None, 2))

x是一个张量,它是Placeholder运算的输出:

print(x.op.type) # Placeholder

as_graph_def()返回图形的序列化版本(将其视为文本版本)。get_operation()返回实际操作,而不是它们的序列化表示。当您打印这些操作(或将它们写入文件)时,您将获得相同的值,因为__str__()操作的方法返回其序列化形式。

你不会总是得到相同的值。例如:

import tensorflow as tf
import numpy as np
tf.reset_default_graph()

v = tf.Variable(np.random.normal([1]))
res1, res2 = [], []

for n in v.graph.as_graph_def(add_shapes=False).node:
    res1.append(n.__str__())

for op in tf.get_default_graph().get_operations():
    res2.append(op.__str__())
print(set(res1) == set(res2)) # True <-- exact same representation
res1, res2 = [], []

for n in v.graph.as_graph_def(add_shapes=True).node:
    res1.append(n.__str__())

for op in tf.get_default_graph().get_operations():
    res2.append(op.__str__())
print(set(res1) == set(res2)) # False <-- not the same in this case!

有关更多信息,您可以参考原始 tensorflow论文


推荐阅读