我无法理解 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 图是一个有向图,这样:
- 节点 - 操作 (ops)。
- 有向边 - 张量。
例如,当您定义:
x = tf.placeholder(tf.float32, shape=(None, 2))
x
是张量,它是 Placeholder
操作的输出:
print(x.op.type) # Placeholder
as_graph_def()
返回图的 SERIALIZED 版本(将其视为文本版本)。 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原文paper .
关于tensorflow - 节点和操作之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56007914/