一. Tensorflow中的基本概念
【1】Graph(圖)來表示計算任務
【2】Session(會話)執(zhí)行Graph
【3】Tensor表示數(shù)據(jù)
【4】Variable維護狀態(tài)
【5】Feed和Fetch為任意的操作賦值或者從中獲取數(shù)據(jù)
【6】Tensor(張量)是某一類型的多維數(shù)組
【7】OP節(jié)點操作
二. Tensorflow的計算圖
TensorFlow是基于計算流圖的,其命名來源于自身的運行原理。Tensorflow使用圖來表示計算任務,如下圖所示:

所以Tensorflow的程序通常分為
構建階段和執(zhí)行階段。執(zhí)行的過程就是tensor在計算圖中的flow,所以稱之為Tensorflow。
# -*- coding: UTF-8 -*-
import tensorflow as tf
# 創(chuàng)建常量op
a = tf.constant([1, 2, 3])
b = tf.constant([4, 5 ,6])
# 創(chuàng)建add的op
c = tf.add(a, b)
print('c before:', c)
# 建立session,用with即用python中的上下文管理器管理這個session,當上下文管理器退出時,會釋放資源,結束session
with tf.Session() as sess:
print(sess.run(c))
輸出的結果為:
('c before:', <tf.Tensor 'Add:0' shape=(3,) dtype=int32>)
[5 7 9]
通過session,數(shù)據(jù)才能在計算圖中流動起來,這時候可以得到具體的數(shù)值。
(1) Fetch
取回操作是使用Session對象的run()調(diào)用執(zhí)行圖時,傳入tensor,這些tensor會幫助我們?nèi)』亟Y果。
上面的例子我們只取回了一個tensor,也可以取回多個tensor
# -*- coding: UTF-8 -*-
import tensorflow as tf
# 創(chuàng)建常量op
a = tf.constant([1, 2, 3])
b = tf.constant([4, 5 ,6])
# 創(chuàng)建add的op
c = tf.add(a, b)
d = a+c
print('c before:', c)
# 建立session,用with即用python中的上下文管理器管理這個session,當上下文管理器退出時,會釋放資源,結束session
with tf.Session() as sess:
print(sess.run([c, d]))
(2) Feed
feed可以理解為一個占位符,當運行的時候可以臨時代替計算圖中任意操作中的tensor。
# -*- coding: UTF-8 -*-
import tensorflow as tf
# 創(chuàng)建常量op
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
# 創(chuàng)建add的op
c = tf.add(a, b)
# 建立session,用with即用python中的上下文管理器管理這個session,當上下文管理器退出時,會釋放資源,結束session
with tf.Session() as sess:
print(sess.run(c, feed_dict={a: [1.], b: [2.]}))
這里的placeholder就是占位符,在run的時候feed具體的數(shù)值。