這幾天在看面向機器智能的tensorflow實踐這本教材,在第三章的最後有一個執行個體,我照着敲了代碼看看結果,由于書本中用的是低版本的tensdoflow是以有些代碼進行了修改,修改過程中踩了一些坑,最後還是調試出來了。
import tensorflow as tf
graph = tf.Graph() # 顯式建立一個Graph對象
with graph.as_default():
with tf.name_scope("variables"):
# 追蹤資料流程圖運作次數的Variables對象
global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name="global_step")
# 追蹤所有輸出随時間的累加和的Variables對象
total_output = tf.Variable(0.0, dtype=tf.float32, trainable=False, name="total_output")
# 主要變換的OP
with tf.name_scope("transformation"):
# 獨立的輸入層
with tf.name_scope("input"):
# 建立可接收一個向量的占位符
a = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_a")
# 獨立的中間層
with tf.name_scope("intermediate_layer"):
b = tf.reduce_prod(a, name="product_b")
c = tf.reduce_sum(a, name="sum_c")
# 獨立的輸出層
with tf.name_scope("output"):
output = tf.add(b, c, name="output")
with tf.name_scope("update"):
# 用最新的輸出更新Variable對象total_output
update_total = total_output.assign_add(output)
# 将前面的Variable對象global_step增1,隻要資料流程圖運作,該操作便需要進行
increment_step = global_step.assign_add(1)
# 彙總OP
with tf.name_scope("summaries"):
avg = tf.div(update_total, tf.cast(increment_step, tf.float32), name="average")
# 為輸出節點建立彙總資料
tf.summary.scalar('output_summary', output)
tf.summary.scalar('total_summary', update_total)
tf.summary.scalar('average_summary', avg)
# 全局Variable對象和OP
with tf.name_scope("global_ops"):
# 初始化OP
init = tf.global_variables_initializer() # 已修改為最新函數
# 将所有彙總資料合并到一個OP中
merged_summaries = tf.summary.merge_all()
# 用明确建立的Graph對象啟動一個會話
sess = tf.Session(graph=graph)
# 開啟一個Summary.FileWriter對象,儲存彙總資料
writer = tf.summary.FileWriter('tmp1', sess.graph)
# 初始化Variable對象
sess.run(init)
def run_graph(input_tensor):
"""
輔助函數;用給定的輸入張量運作資料流程圖,
并儲存彙總資料
:param input_tensor:
:return:
"""
feed_dict = {a: input_tensor}
_, step, summary = sess.run([output, increment_step, merged_summaries], feed_dict=feed_dict)
writer.add_summary(summary, global_step=step)
# 用不同的輸入運作該資料流程圖
run_graph([2, 8])
run_graph([3, 1, 3, 3])
run_graph([8])
run_graph([1, 2, 3])
run_graph([11, 4])
run_graph([4, 1])
run_graph([7, 3, 1])
run_graph([6, 3])
run_graph([0, 2])
run_graph([4, 5, 6])
# 将彙總資料寫入磁盤
writer.flush()
# 關閉writer對象
writer.close()
# 關閉Session對象
sess.close()
運作完成後通過指令打開tensorboard,如圖:
提示:summary界面預設不顯示summary圖(你可以看到summary最右邊标了個3,代表有三張圖),點選summary就能看到了(開始我以為自己代碼有問題,半天沒找到,原來需要點選下)。