圖(graph)是TensorFlow用于表達(dá)計(jì)算任務(wù)的一個(gè)核心概念。
Graph
graph被定義為一些operation和tensor的集合。例如,
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
c = tf.placeholder(tf.float32)
d = a*b+c
e = d*2
該圖如下,其中每個(gè)圓圈表示一個(gè)operation,橢圓到橢圓的邊為tensor,箭頭的指向表示了這張圖operation輸入輸出tensor的傳遞關(guān)系。

圖
在TensorFlow運(yùn)行時(shí),Python構(gòu)建的“圖”并不是啟動(dòng)一個(gè)session之后始終不變的,TensorFlow先將Python代碼描繪的圖轉(zhuǎn)換成protocol buffer,再通過(guò)c/c++/cuda運(yùn)行protocol buffer所定義的圖。
graphdef
從Python graph中序列化出來(lái)的圖為graphdef,是由許多protocol buffer組成的。
node {
name: "Placeholder" # 注釋?zhuān)哼@是一個(gè)叫做 "Placeholder" 的node
op: "Placeholder"
attr {
key: "dtype"
value {
type: DT_FLOAT
}
}
attr {
key: "shape"
value {
shape {
unknown_rank: true
}
}
}
}
node {
name: "Placeholder_1" # 注釋?zhuān)哼@是一個(gè)叫做 "Placeholder_1" 的node
op: "Placeholder"
attr {
key: "dtype"
value {
type: DT_FLOAT
}
}
attr {
key: "shape"
value {
shape {
unknown_rank: true
}
}
}
}
node {
name: "mul" # 注釋?zhuān)阂粋€(gè) Mul(乘法)操作
op: "Mul"
input: "Placeholder" # 使用上面的node(即Placeholder和Placeholder_1)
input: "Placeholder_1" # 作為這個(gè)Node的輸入
attr {
key: "T"
value {
type: DT_FLOAT
}
}
}
以上三個(gè)nodedef定義了兩個(gè)placeholder和一個(gè)木