1. 程式人生 > >tensorflow:實戰google深度學習框架

tensorflow:實戰google深度學習框架

第一章

1.  簡介

第二章

1.  安裝

安裝方法在我的部落格有,包括cpu版,gpu版。

 

第三章 TensorFlow入門

1.  計算圖

constant是TensorFlow的常量節點,通過constant方法建立,其是計算圖(Computational Graph)中的起始節點,是傳入資料。

cons = tf.constant(value=[1,2],dtype=tf.float32,shape=(1,2),name='testconst', verify_shape=False)

 

  • 使用圖 (graph) 來表示計算任務.
  • 在被稱之為 會話 (Session) 的上下文 (context) 中執行圖.
  • 使用 tensor 表示資料.
  • 通過 變數 (Variable) 維護狀態.
  • 使用 feed 和 fetch 可以為任意的操作(arbitrary operation) 賦值或者從其中獲取資料

為了進行計算, 圖必須在 會話 裡被啟動. 會話 將圖的 op 分發到諸如 CPU 或 GPU 之類的 裝置 上, 同時提供執行 op 的方法. 這些方法執行後, 將產生的 tensor 返回. 在 Python 語言中, 返回的 tensor 是 numpy ndarray 物件

 

構建圖的第一步, 是建立源 op (source op). 源 op 不需要任何輸入, 例如 常量 (Constant). 源 op 的輸出被傳遞給其它 op 做運算.

構造階段完成後, 才能啟動圖. 啟動圖的第一步是建立一個 Session 物件, 如果無任何建立引數, 會話構造器將啟動預設圖.

Session 物件在使用完後需要關閉以釋放資源. 除了顯式呼叫 close 外, 也可以使用 "with" 程式碼塊 來自動完成關閉動作.

with tf.Session() as sess:
  result = sess.run([product])
  print result

如果機器上有超過一個可用的 GPU, 除第一個外的其它 GPU 預設是不參與計算的. 為了讓 TensorFlow 使用這些 GPU, 你必須將 op 明確指派給它們執行. with...Device 語句用來指派特定的 CPU 或 GPU 執行操作:

with tf.Session() as sess:
  with tf.device("/gpu:1"):
    matrix1 = tf.constant([[3., 3.]])
    matrix2 = tf.constant([[2.],[2.]])
    product = tf.matmul(matrix1, matrix2)
    ...

ensorFlow 程式使用 tensor 資料結構來代表所有的資料, 計算圖中, 操作間傳遞的資料都是 tensor. 你可以把 TensorFlow tensor 看作是一個 n 維的陣列或列表. 一個 tensor 包含一個靜態型別 rank, 和 一個 shape

assign

x.assign(1)

update = tf.assign(x, 2)

# 建立一個變數, 初始化為標量 0.
state = tf.Variable(0, name="counter")

# 建立一個 op, 其作用是使 state 增加 1

one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)

# 啟動圖後, 變數必須先經過`初始化` (init) op 初始化,
# 首先必須增加一個`初始化` op 到圖中.
init_op = tf.initialize_all_variables()

# 啟動圖, 執行 op
with tf.Session() as sess:
  # 執行 'init' op
  sess.run(init_op)
  # 列印 'state' 的初始值
  print sess.run(state)
  # 執行 op, 更新 'state', 並列印 'state'
  for _ in range(3):
    sess.run(update)
    print sess.run(state)

程式碼中 assign() 操作是圖所描繪的表示式的一部分, 正如 add() 操作一樣. 所以在呼叫 run() 執行表示式之前, 它並不會真正執行賦值操作.

 

fetch和feed機制

tf.placeholder() 為這些操作建立佔位符

input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.mul(input1, input2)

with tf.Session() as sess:
  print sess.run([output], feed_dict={input1:[7.], input2:[2.]})