您的位置:首页 > 其它

Tensorflow使用技巧:通过graph.as_graph_def探索函数内部机制

2017-07-20 18:08 639 查看
Tensorflow有tf.Graph类,用于存储计算图。而计算图其实就是由节点和有向边组成,每个点包括操作Op、数值value、类型dtype、形状shape等属性。探索诸如tf.Variable()等函数的内部机制的过程中,就需要查看计算图的变化情况,包括新建了哪些节点,输入是什么等等。

例如想要探讨tf.constant函数的内部机制,则运行以下代码:

import tensorflow as tf

a = tf.constant(1)
print(tf.get_default_graph().as_graph_def())


返回

node {
name: "Const"
op: "Const"
attr {
key: "dtype"
value {
type: DT_INT32
}
}
attr {
key: "value"
value {
tensor {
dtype: DT_INT32
tensor_shape {
}
int_val: 1
}
}
}
}
versions {
producer: 22
}


就可以判断tf.constant函数其实仍然是有Operation的,为const,而值是用属性attr存储的。

进一步探讨tf.Variable机制,则同样运行以下代码:

import tensorflow as tf

a = tf.constant(1)
b = tf.Variable(a)
print(tf.get_default_graph().as_graph_def())


返回如下结果:

node {
name: "ones"
op: "Const"
attr {
key: "dtype"
value {
type: DT_FLOAT
}
}
attr {
key: "value"
value {
tensor {
dtype: DT_FLOAT
tensor_shape {
dim {
size: 1
}
}
float_val: 1.0
}
}
}
}
node {
name: "Variable"
op: "VariableV2"
attr {
key: "container"
value {
s: ""
}
}
attr {
key: "dtype"
value {
type: DT_FLOAT
}
}
attr {
key: "shape"
value {
shape {
dim {
size: 1
}
}
}
}
attr {
key: "shared_name"
value {
s: ""
}
}
}
node {
name: "Variable/Assign"
op: "Assign"
input: "Variable"
input: "ones"
attr {
key: "T"
value {
type: DT_FLOAT
}
}
attr {
key: "_class"
value {
list {
s: "loc:@Variable"
}
}
}
attr {
key: "use_locking"
value {
b: true
}
}
attr {
key: "validate_shape"
value {
b: true
}
}
}
node {
name: "Variable/read"
op: "Identity"
input: "Variable"
attr {
key: "T"
value {
type: DT_FLOAT
}
}
attr {
key: "_class"
value {
list {
s: "loc:@Variable"
}
}
}
}
versions {
producer: 22
}


发现虽然只是运行了一行代码,但是实际上添加了三个节点,分别是Variable、Variable/read和Variable/Assign,从字面理解可以猜测分别是作为存储器、读取接口和赋值接口。而这个assign的存在就是区分Variable和Tensor的重要标志(Variable是mutable的)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息