TensorBoard:可視化學習

我是一個很懶的人弃酌,我想試試

希望我能堅持到最后,把tensorflow的官方教程全部翻譯出來

提高自己芒涡,也幫助他人

TensorBoard: Visualizing Learning

使用 TensorFlow 計算普气,如訓練一個大型的深度神經(jīng)網(wǎng)絡唐断,可能會非常的復雜與難以理解。為了使其容易理解澎怒,調(diào)試和優(yōu)化 TensorFlow 程序褒搔,我們有一套叫做 TensorBoard 的可視化工具。你可以使用 TensorBoard 可視化你的 TensorFlow 圖喷面,繪制圖執(zhí)行的量化指標星瘾,并通過它以圖像的形式顯示附加的數(shù)據(jù)。當 TensorBoard 設(shè)置完成后惧辈,它看起來就像下面這樣:

MNIST TensorBoard

本教程旨在教會你入門簡單的 TensorBoard 用法琳状。還有其他的資源是可用的。如 TensorBoard's GitHub 有很多關(guān)于 TensorBoard 使用的信息盒齿,包括了提示念逞,技巧以及調(diào)試信息。

Serializing the data

TensorBoard 通過讀取 TensorFlow 事件文件來操作边翁,它包括了運行 TensorFlow 過程中生成的匯總數(shù)據(jù)翎承。以下是 TensorBoard 在一般的生命周期中產(chǎn)生的匯總數(shù)據(jù)。

首先符匾,創(chuàng)建你想要收集匯總數(shù)據(jù)的 TensorFlow 圖叨咖,并決定你想要哪個節(jié)點使用 匯總操作 注釋(annotate)。

例如,假設(shè)你要訓練一個卷積神經(jīng)網(wǎng)絡識別 MNIST 數(shù)字甸各,你想要記錄在整個訓練過程中學習率是如何變化的垛贤,目標函數(shù)是如何變化的。通過向節(jié)點附加 tf.summary.scalar 操作來收集這些數(shù)據(jù)趣倾,并分別輸出學習率和損失聘惦。然后給每個 scalar_summary 一個有意義的 tag,如'learning rate' or 'loss function' 誊酌。

也許你想要可視化一個特定層的激活分布部凑,或者梯度或者權(quán)重的分布”套牵可以通過分別向梯度輸出和權(quán)重變量附加 tf.summary.histogram 操作來收集這些數(shù)據(jù)。

有關(guān)可用的匯總操作的所有詳細信息瘟仿,請查閱有關(guān)文檔summary operations 箱锐。

在 TensorFlow 中,操作只有當你執(zhí)行或者一個操作依賴它的輸出時才會執(zhí)行劳较。我們創(chuàng)建的匯總節(jié)點(summary nodes)都圍繞在你的圖的邊上:沒有一個操作的運行是依賴它們的驹止。所以,為了生成匯總節(jié)點观蜗,我們需要運行所有的匯總節(jié)點臊恋。手動管理這些是很乏味的,所以使用 tf.summary.merge_all 聯(lián)合它們到一個操作來生成所有的匯總數(shù)據(jù)墓捻。

然后你可以只執(zhí)行合并匯總操作抖仅,它將在一個給定的步驟將所有的匯總數(shù)據(jù)生成一個序列化的Summary protobuf 對象。最后砖第,為了將這個匯總數(shù)據(jù)寫入到硬盤撤卢,傳遞匯總 protobuf 到tf.summary.FileWriter

FileWriter 的構(gòu)造函數(shù)是帶有 logdir 參數(shù)的——這個 logdir 非常重要梧兼,是所有的事件輸出的目錄放吩。FileWriter 在構(gòu)造函數(shù)中也可以使用Graph 這個可選參數(shù)。如果接收到一個Graph 對象羽杰,那么 TensorBoard 將隨著張量 shape 信息可視化 graph渡紫。這將使你更好的理解圖中運行情況:請查閱 Tensor shape information

注意你已經(jīng)修改了你的 graph考赛,并有了一個 FileWriter 惕澎,你已準備開始運行你的網(wǎng)絡了!如果你需要欲虚,你可以在每一步中運行合并匯總操作并保存大量的訓練數(shù)據(jù)集灌。這樣你將得到超出你需要的很多的數(shù)據(jù),相反你可以考慮每 n 個步驟運行一次合并匯總操作。

以下代碼實例修改于 simple MNIST tutorial 欣喧,我們只是增加了一些匯總操作腌零,并每十個步驟運行一次它們。如果你運行這個并啟動 tensorboard --logdir=/tmp/tensorflow/mnist 唆阿,你將能夠可視化這些統(tǒng)計數(shù)據(jù)益涧,例如在訓練期間,權(quán)重或者準確率是如何變化的驯鳖。以下只是代碼的部分闲询,完整代碼 在這

def variable_summaries(var):
  """Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
  with tf.name_scope('summaries'):
    mean = tf.reduce_mean(var)
    tf.summary.scalar('mean', mean)
    with tf.name_scope('stddev'):
      stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
    tf.summary.scalar('stddev', stddev)
    tf.summary.scalar('max', tf.reduce_max(var))
    tf.summary.scalar('min', tf.reduce_min(var))
    tf.summary.histogram('histogram', var)

def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu):
  """Reusable code for making a simple neural net layer.

  It does a matrix multiply, bias add, and then uses relu to nonlinearize.
  It also sets up name scoping so that the resultant graph is easy to read,
  and adds a number of summary ops.
  """
  # Adding a name scope ensures logical grouping of the layers in the graph.
  with tf.name_scope(layer_name):
    # This Variable will hold the state of the weights for the layer
    with tf.name_scope('weights'):
      weights = weight_variable([input_dim, output_dim])
      variable_summaries(weights)
    with tf.name_scope('biases'):
      biases = bias_variable([output_dim])
      variable_summaries(biases)
    with tf.name_scope('Wx_plus_b'):
      preactivate = tf.matmul(input_tensor, weights) + biases
      tf.summary.histogram('pre_activations', preactivate)
    activations = act(preactivate, name='activation')
    tf.summary.histogram('activations', activations)
    return activations

hidden1 = nn_layer(x, 784, 500, 'layer1')

with tf.name_scope('dropout'):
  keep_prob = tf.placeholder(tf.float32)
  tf.summary.scalar('dropout_keep_probability', keep_prob)
  dropped = tf.nn.dropout(hidden1, keep_prob)

# Do not apply softmax activation yet, see below.
y = nn_layer(dropped, 500, 10, 'layer2', act=tf.identity)

with tf.name_scope('cross_entropy'):
  # The raw formulation of cross-entropy,
  #
  # tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.softmax(y)),
  #                               reduction_indices=[1]))
  #
  # can be numerically unstable.
  #
  # So here we use tf.nn.softmax_cross_entropy_with_logits on the
  # raw outputs of the nn_layer above, and then average across
  # the batch.
  diff = tf.nn.softmax_cross_entropy_with_logits(targets=y_, logits=y)
  with tf.name_scope('total'):
    cross_entropy = tf.reduce_mean(diff)
tf.summary.scalar('cross_entropy', cross_entropy)

with tf.name_scope('train'):
  train_step = tf.train.AdamOptimizer(FLAGS.learning_rate).minimize(
      cross_entropy)

with tf.name_scope('accuracy'):
  with tf.name_scope('correct_prediction'):
    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
  with tf.name_scope('accuracy'):
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
tf.summary.scalar('accuracy', accuracy)

# Merge all the summaries and write them out to /tmp/mnist_logs (by default)
merged = tf.summary.merge_all()
train_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/train',
                                      sess.graph)
test_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/test')
tf.global_variables_initializer().run()

在我們初始化 FileWriters 之后浅辙,我們必須在我們訓練和測試模型時附加匯總到 FileWriters 扭弧。

# Train the model, and also write summaries.
# Every 10th step, measure test-set accuracy, and write test summaries
# All other steps, run train_step on training data, & add training summaries

def feed_dict(train):
  """Make a TensorFlow feed_dict: maps data onto Tensor placeholders."""
  if train or FLAGS.fake_data:
    xs, ys = mnist.train.next_batch(100, fake_data=FLAGS.fake_data)
    k = FLAGS.dropout
  else:
    xs, ys = mnist.test.images, mnist.test.labels
    k = 1.0
  return {x: xs, y_: ys, keep_prob: k}

for i in range(FLAGS.max_steps):
  if i % 10 == 0:  # Record summaries and test-set accuracy
    summary, acc = sess.run([merged, accuracy], feed_dict=feed_dict(False))
    test_writer.add_summary(summary, i)
    print('Accuracy at step %s: %s' % (i, acc))
  else:  # Record train set summaries, and train
    summary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True))
    train_writer.add_summary(summary, i)

你現(xiàn)在已經(jīng)準備好使用 TensorBoard 可視化這些數(shù)據(jù)。

Launching TensorBoard

運行 TensorBoard记舆,請使用以下命令(或者 python -m tensorboard.main)

tensorboard --logdir=path/to/log-directory

其中logdir 指向FileWriter 序列化其數(shù)據(jù)的目錄鸽捻。如果logdir 目錄包含單獨運行的序列化數(shù)據(jù)的子目錄,TensorBoard 將可視化所有的這些運行的數(shù)據(jù)泽腮。一旦 TensorBoard 運行起來御蒲,輸入 localhost:6006 到你的 web 瀏覽器,已查看 TensorBoard诊赊。

當瀏覽 TensorBoard 時厚满,你將在右上角看到導航標簽。每個標簽表示可以可視化的一系列序列化數(shù)據(jù)碧磅。

有關(guān)如何使用 graph 選項卡可視化圖的更多信息碘箍,請查閱 TensorBoard: Graph Visualization

有關(guān) TensorBoard 的更多的使用信息续崖,請查閱 TensorBoard's GitHub 敲街。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市严望,隨后出現(xiàn)的幾起案子多艇,更是在濱河造成了極大的恐慌,老刑警劉巖像吻,帶你破解...
    沈念sama閱讀 216,997評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件峻黍,死亡現(xiàn)場離奇詭異,居然都是意外死亡拨匆,警方通過查閱死者的電腦和手機姆涩,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來惭每,“玉大人骨饿,你說我怎么就攤上這事亏栈。” “怎么了宏赘?”我有些...
    開封第一講書人閱讀 163,359評論 0 353
  • 文/不壞的土叔 我叫張陵绒北,是天一觀的道長。 經(jīng)常有香客問我察署,道長闷游,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,309評論 1 292
  • 正文 為了忘掉前任贴汪,我火速辦了婚禮脐往,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘扳埂。我一直安慰自己业簿,他們只是感情好,可當我...
    茶點故事閱讀 67,346評論 6 390
  • 文/花漫 我一把揭開白布聂喇。 她就那樣靜靜地躺著辖源,像睡著了一般。 火紅的嫁衣襯著肌膚如雪希太。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,258評論 1 300
  • 那天酝蜒,我揣著相機與錄音誊辉,去河邊找鬼。 笑死亡脑,一個胖子當著我的面吹牛堕澄,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播霉咨,決...
    沈念sama閱讀 40,122評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼蛙紫,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了途戒?” 一聲冷哼從身側(cè)響起坑傅,我...
    開封第一講書人閱讀 38,970評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎喷斋,沒想到半個月后唁毒,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,403評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡星爪,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,596評論 3 334
  • 正文 我和宋清朗相戀三年浆西,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片顽腾。...
    茶點故事閱讀 39,769評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡近零,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情久信,我是刑警寧澤窖杀,帶...
    沈念sama閱讀 35,464評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站入篮,受9級特大地震影響陈瘦,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜潮售,卻給世界環(huán)境...
    茶點故事閱讀 41,075評論 3 327
  • 文/蒙蒙 一痊项、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧酥诽,春花似錦鞍泉、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至训枢,卻和暖如春托修,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背恒界。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評論 1 269
  • 我被黑心中介騙來泰國打工睦刃, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人十酣。 一個月前我還...
    沈念sama閱讀 47,831評論 2 370
  • 正文 我出身青樓涩拙,卻偏偏與公主長得像,于是被迫代替她去往敵國和親耸采。 傳聞我的和親對象是個殘疾皇子兴泥,可洞房花燭夜當晚...
    茶點故事閱讀 44,678評論 2 354

推薦閱讀更多精彩內(nèi)容