tensorflow - 节点和操作之间的区别
问题描述
我不明白 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()
返回图形的序列化版本(将其视为文本版本)。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论文。
推荐阅读
- javascript - 无法让matter.js 启动
- database - 如何将 datagrip 设置为与主机数据库相同的时区
- c++ - 信号量实现 - notify() 是否应该在通知 condition_variable 之前释放互斥锁?
- ghost-blog - 我们可以在 Ghost 3.0 上使用 Haunted 主题吗
- java - 如何修复 [删除类型] 在搜索请求中指定类型已弃用。”](elasticsearch 7.4.0,spring boot 2.2.6)?
- java - 使用自定义图像进行 Java 碰撞检测
- c++ - 删除名称中包含单词的文件。C++
- node.js - Express-Validator 条件验证
- python - 在 OMpython 中使用 OPCUA 进行交互式仿真
- jmeter - 动态并行 HTTP 请求