4用於cifar10的卷積神經網路-4.7TensorFlow的彙總類Summary和FileWriter用法
Summary類:負責彙總資料並寫入事件檔案
TensorBoard前臺呈現的資料時tensorflow程式執行過程中,將一些summary型別的資料寫入到日誌目錄的event檔案中。下圖示識了資料寫入過程。
使用TensorBoard展示資料,需要在執行TensorFlow計算圖的過程中,將各種型別的資料彙總並記錄到日誌檔案中。然後使用TensorBoard讀取這些日誌檔案,解析資料並生產資料視覺化的web頁面,讓我們可以在瀏覽器中觀察各種彙總資料。
summary_op包括了summary.scalar 、summary.histogram、summary.image等操作,這些操作輸出的是各種summary protobuf,最後通過summary.writer寫入到event檔案中。
TensorFlow API中包含系列生產summary資料的API介面,這些函式將彙總資訊存放在protobuf中,以字串形式表達。
Summary類的彙總操作合併方法
將上面幾種型別的彙總再進行一次合併,具體合併哪些由inputs指定,格式如下:
tf.summary.merge(inputs, collections=None, name=None)
合併預設圖形中的所有彙總:
merged_summaries=tf.summary.merge_all(key='summaries')
牢記:merged_summaries是一個節點,必須先傳入session.run()執行才能獲得真正的彙總!
summary.FileWriter:將彙總結果寫入事件(event file)
class FileWriter(SummaryToEventTransformer):
"""Writes `Summary` protocol buffers to event files.
The `FileWriter` class provides a mechanism to create an event file in a
given directory and add summaries and events to it. The class updates the
file contents asynchronously. This allows a training program to call methods
to add data to the file directly from the training loop, without slowing down
training.
"""
"""
把 `Summary` protocol buffers 寫入到event files。
這個`FileWriter`類提供了一個機制,能夠在指定的目錄下面建立event檔案,然後將快取中的summaries寫入到event檔案中去。
該類可以非同步的更新(updates asynchronously)events檔案的內容。
這個非同步機制能夠讓程式在訓練迴圈過程中呼叫add方法直接往檔案中新增資料而不用阻塞迴圈訓練過程導致訓練速度減慢。
"""
注意:
add_summary僅僅是向FileWriter物件的快取中存放event data。而向disk上寫資料是由FileWrite物件控制的。
tf.summary.FileWriter.__init__(self,
logdir,
graph=None,
max_queue=10,
flush_secs=120,
graph_def=None):
Creates a `FileWriter` and an event file.
Args:
logdir: A string. Directory where event file will be written.
graph: A `Graph` object, such as `sess.graph`.
max_queue: Integer. Size of the queue for pending events and summaries.
flush_secs: Number. How often, in seconds, to flush the pending events and summaries to disk.
graph_def: DEPRECATED: Use the `graph` argument instead.
#max_queue:在向disk寫資料之前,最大能夠快取event的個數
#flush_secs:每多少秒向disk中寫資料,並清空物件快取
使用的時候需要注意的地方:
1、 如果使用filewriter.add_summary(summary, global_step)時沒有傳global_step引數,會使scarlar_summary變成一條直線。
2、只要是在計算圖上的Summary op,都會被merge_all捕捉到,不需要考慮變數生存空間問題!
3、如果執行一次,disk上沒有儲存Summary資料的話,可以嘗試下filewriter.flush()
name_scope:讓生成的彙總有層次性
典型的TensorFlow可以有數以千計的節點,如此多而難以一下全部看到,甚至無法使用標準圖表工具來展示。為了簡單起見,我們為變數名劃定範圍,並且視覺化把該資訊用於在圖表中的節點上定義一個層級。預設情況下,只有頂層節點會顯示。
name_scope還可以用於資料的彙總,讓TensorBoard中的彙總資料也更有層次。
如果想要生成的summary有層次的話,記得在summary外面加一個name_scope
with tf.name_scope('summary_gradients'):
tf.summary.histogram("name",gradients)
這樣,tensorboard在顯示的時候,就會有一個summary_gradients目錄